gpt4 book ai didi

javascript - 使用 json 填充下拉列表(SyntaxError : Unexpected token { in JSON. 。)

转载 作者:行者123 更新时间:2023-12-02 21:24:13 24 4
gpt4 key购买 nike

我试图简单地使用 JSON 数据文件中的 styleName 字段值填充下拉列表。

例如,我的 json 数据如下所示:

{"name":{"styleName":"name","fillType":"none","fillTrans":"0","outlineType":"solid","outlineWidth":"1","outlineColor":"#ff0000"}}  
{"sarah":{"styleName":"sarah","fillTrans":"none","fillTrans":"0","outlineType":"solid","outlineWidth":"1","outlineColor":"#ff0000"}}
//....

下面是我的 JS。

<小时/>
let dropdown = document.getElementById('tem');

dropdown.length = 0;

let defaultOption = document.createElement('option');
defaultOption.text = 'Choose Template';

dropdown.add(defaultOption);
dropdown.selectedIndex = 0;

const urld = '../../templates.json';

fetch(urld)
.then(
function(response) {
if (response.status !== 200) {
console.warn('Looks like there was a problem. Status Code: ' +
response.status);
return;
}

// Examine the text in the response
response.json().then(function(data) {
let option;
console.log(data);
for (let i = 0; i < data.length; i++) {
option = document.createElement('option');
option.text = data[i].styleName;
//option.value = data[i].abbreviation;
dropdown.add(option);
}
});
}
)
.catch(function(err) {
console.error('Fetch Error -', err);
});
<小时/>

我不断收到此错误,尽管响应 200,但下拉列表仍为空白。错误:

Uncaught (in promise) SyntaxError: Unexpected token { in JSON at position xxx
Promise.then (async)
(anonymous) @ VM8493:22
Promise.then (async)
(anonymous) @ VM8493:13

下拉标记就是这样:

                    <select id="tem" class='w150'>
</select>

最佳答案

 replace this option.text = data[i].styleName;
let keys=Object.keys(data[i])
with option.text = data[i][keys[0]].styleName

关于javascript - 使用 json 填充下拉列表(SyntaxError : Unexpected token { in JSON. 。),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60778931/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com