我正在尝试使用外部select
文件中的数据填充json
元素。
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
{
"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"
}
]
}
}
我已经可以使用上述方法成功返回数据,但是由于某些原因,我无法运行循环,并且不确定自己在做什么错。
没有控制台错误,我的警报也不会触发...
答案 0 :(得分:0)
向选项中添加选项的最佳方法是根据W3schools Select add() Method使用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>
答案 1 :(得分:0)
您需要以这种方式编写代码。
数据正在返回#include <string.h>
void mat_insert(const struct matrix *s, struct matrix *d, int r, int c)
{ // copy source matrix s to destination matrix d at row r, column c
for (int i = 0; i < s->M; i++) // for each row
memcpy(d->data+(r+i)*d->N+c, s->data+i*s->N, s->N*sizeof*s->data);
}
struct matrix *mat_directsum(const struct matrix *a, const struct matrix *b)
{
struct matrix *c = malloc(sizeof *c); if (!c) return NULL;
c->M = a->M + b->M;
c->N = a->N + b->N;
int n = c->M * c->N;
c->data = calloc(n, sizeof *c->data); if (!c->data) return free(c), NULL;
mat_insert(a, c, 0, 0); // copy a to c at row 0, column 0
mat_insert(b, c, a->M, a->N); // copy b to c at row a->M, column a->N
return c;
}
,因此数据长度为object {}
,并且循环未运行。
您需要选择要返回数组的特定数据。
例如:undefined
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;