[英]Populate select element using Vanilla JS and JSON file
I'm trying to populate a select
element using data from an external json
file. 我正在尝试使用来自外部
json
文件的数据填充select
元素。
var dropDown = document.getElementById('dropdown');
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// success
data = JSON.parse(request.responseText);
console.log(data);
for (var i = 0, len = data.length; i < len; i++) {
alert('FOO');
var data = data[i];
dropDown.innerHTML(option.name);
}
};
JSON JSON
{
"TopLevel": {
"Second": [
"data",
"data",
"data",
"data"
],
"Second": [
{
"ThirdLabel": "data",
"ThirdID": "data"
},
{
"ThirdLabel": "data",
"ThirdID": "data"
},
{
"ThirdLabel": "data",
"ThirdID": "data"
}
]
},
"TopLevel": {
"Second": [
"data",
"data",
"data",
"data"
],
"Second": [
{
"ThirdLabel": "data",
"ThirdID": "data"
},
{
"ThirdLabel": "data",
"ThirdID": "data"
},
{
"ThirdLabel": "data",
"ThirdID": "data"
}
]
}
}
I've can successfully return my data using the above but for some reason I cant get the loop to run and im unsure what I'm doing wrong. 我已经可以使用上述方法成功返回数据,但是由于某些原因,我无法使循环运行并且不确定自己在做什么错。
There's no console errors and my alert doesn't fire... 没有控制台错误,我的警报也不会触发...
The best way to add option to a select is using document.createElement("option")
according to W3schools Select add() Method . 向选项添加选项的最佳方法是根据W3schools Select add()方法使用
document.createElement("option")
。
var json = { "data": ["orange", "banana", "apple", "pear"] }; var dropdown = document.getElementById("dropdown"); for (var i = 0; i < json.data.length; i++) { var option = document.createElement("option"); option.text = json.data[i]; option.value = json.data[i]; dropdown.add(option); }
<select id="dropdown"></select>
You need to write code in this way. 您需要以这种方式编写代码。
The data is returning object {}
therefore the length of the data is undefined
and loop is not running. 数据正在返回
object {}
因此数据的长度undefined
并且循环未运行。
You need to select particular data which will return array. 您需要选择将返回数组的特定数据。
Ex: data.TopLevel.Second
例如:
data.TopLevel.Second
var data = { "TopLevel": { "Second": [ "data", "data", "data", "data" ], "Second": [{ "ThirdLabel": "data", "ThirdID": "data" }, { "ThirdLabel": "data", "ThirdID": "data" }, { "ThirdLabel": "data", "ThirdID": "data" } ] }, "TopLevel": { "Second": [ "data", "data", "data", "data" ], "Second": [{ "ThirdLabel": "data", "ThirdID": "data" }, { "ThirdLabel": "data", "ThirdID": "data" }, { "ThirdLabel": "data", "ThirdID": "data" } ] } } var dropDown = document.getElementById('dropdown'); debugger; var options = ""; for (var i = 0, len = data.TopLevel.Second.length; i < len; i++) { var item = data.TopLevel.Second[i]; options += "<option> " + item.ThirdID + "</option>" } document.getElementById("dropdown").innerHTML = options;
<select name="" id="dropdown"></select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.