我试图从JSON文件中获取一个填充字符串的列表。它适用于一个字符串' name',但当我尝试添加另一个字符串' age'它得到一个未定义的错误。
(部分)HTML文件
<ul id="people"></ul>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(xhttp.responseText);
var people = response.people;
var output = '';
for(var i = 0;i < people.length;i++){
output += '<li>'+people[i].name+'</li>';
}
document.getElementById('people').innerHTML = output;
}
};
xhttp.open("GET", "people.json", true);
xhttp.send();
// json file //
{
"highscore": [
{
"name":"Billy",
"age": 12,
"date": 11 "november" 2017,
"wins": 4
},
{
"name":"Willem",
"age": 16,
"date": 14 "juni" 2017,
"wins":2
},
{
"name":"Sara",
"age": 14,
"date": 18 "mei" 2017,
"wins": 1
},
{
"name":"Jeff",
"age": 11,
"date": 2 "april" 2017,
"wins":1
}
]
}
答案 0 :(得分:1)
您的json文件有一种奇怪的(可能是错误的)值:
“日期”:11 “11月” 2017,
我不知道你是否可以用这样的值创建一个json文件。
但你可以这样做:
peoples =[
{
"name":"Billy",
"age": 12,
"date": '11 november 2017',
"wins": 4
},
{
"name":"Willem",
"age": 16,
"date": '14 juni 2017',
"wins":2
},
{
"name":"Sara",
"age": 14,
"date": '18 mei 2017',
"wins": 1
},
{
"name":"Jeff",
"age": 11,
"date": '2 april 2017',
"wins":1
}
]
var people = peoples
var output = '';
for(var i = 0;i < people.length;i++){
output += '<li>'+people[i].name + ':' +people[i].age+'</li>';
}
document.getElementById('people').innerHTML = output;
<ul id="people"></ul>