我有3个档案
index.html
data.json
app.js
在我的WAMP服务器上。我希望遍历JSON数据并更新HTML文件的内容。
这些是我文件的内容:
data.json
{
"user": [{
"goal": "HTML essential training",
"type": "Beginner",
"date": "20/07/2016"
}, {
"goal": "CSS essential training",
"type": "Beginner",
"date": "30/07/2016"
}, {
"goal": "CSS core concepts",
"type": "Intermediate",
"date": "10/08/2016"
}, {
"goal": "Javascript essential training",
"type": "Beginner",
"date": "20/08/2016"
}, {
"goal": "Object Oriented JS",
"type": "Advanced",
"date": "30/08/2016"
}]
}
app.js
var request = new XMLHttpRequest();
request.open('GET', 'data.json');
request.onreadystatechange = function() {
if ((request.readyState === 4) && (request.status === 200)) {
var items = JSON.parse(request.responseText);
console.log(items);
for (var key in items) {
console.log(key);
var output = "<tr><td><input type='checkbox' name='record'></td><td>" + items[key].goal + "</td><td>" + items[key].type + "</td><td>" + items[key].date + "</td></tr>";
console.log(output);
$("table tbody").append(output);
output = '';
}
}
}
request.send();
当我运行此代码时,将创建一行并将所有值设置为undefined。我认为我的循环逻辑有问题。请帮助我。
最佳答案
由于返回的对象是单个key: value
对,因此您正在遇到这种情况。
您需要访问作为数组的user
属性。
您的代码
var items=JSON.parse(request.responseText);
解析json字符串后获得的值是带有
key
的JavaScript对象:'user'和value
:这是一个数组应该是
var data =JSON.parse(request.responseText);
var items = data.user; <-- this is an array of objects
// iterate using a for loop, since it is not an object technically
for(var i=0; i < items.length; i++) {