$.getJSON('SampleUserData.json', function(data) {
var output="<ul>";
$.each(data, function (index, val) {
output+="<li>" + String(val.id) + " " + String(val.lastName) + "--" +"</li>";
})
output+="</ul>";
document.getElementById("placeholder").innerHTML=output;
});
返回
undefined undefined--
undefined undefined--
undefined undefined--
undefined undefined--
undefined undefined--
undefined undefined--
undefined undefined--
JSON位于
之下[
{
"First Name": "Pascale",
"Last Name": "Hood",
"Address": "827-448 Magna Rd.",
"City": "Burlington",
"Zip": "38459",
"ID": "71480845"
},
{
"First Name": "Odette",
"Last Name": "Rich",
"Address": "7923 Pede. Rd.",
"City": "Bothey",
"Zip": "14394",
"ID": "65839483"
},
{
"First Name": "Christen",
"Last Name": "Hardin",
"Address": "390-1605 Adipiscing Street",
"City": "Oudergem",
"Zip": "90085",
"ID": "78046404"
},
{
"First Name": "Uma",
"Last Name": "Cunningham",
"Address": "313-1839 Lorem Av.",
"City": "San Cristóbal de la Laguna",
"Zip": "99153",
"ID": "27367690"
}
]
任何帮助都将不胜感激。
答案 0 :(得分:0)
有一些改进的机会以及您遇到的原始问题的解决方案。
$.getJSON('SampleUserData.json', function(records) {
var $ul = $('<ul></ul>');
$ul.append(records.map(function(record) {
return $('<li></li>').text(record['ID'] + ' ' +record['Last Name'] + '--');
}));
$('#userRecordContainer').empty().append($ul);
});
让我们回顾一下:
id
和lastname
应为['ID']
和['Last Name']
。$.fn.text
安全地将文字附加到元素。如果有人的名字恰好包含>
个字符或XSS攻击,那么原始代码就会中断。用于测试的JSFiddle:http://jsfiddle.net/ht31f59m/1/
答案 1 :(得分:-1)
将JSON文件更改为
{"result":
[
{
"First Name": "Pascale",
"Last Name": "Hood",
"Address": "827-448 Magna Rd.",
"City": "Burlington",
"Zip": "38459",
"ID": "71480845"
},
{
"First Name": "Odette",
"Last Name": "Rich",
"Address": "7923 Pede. Rd.",
"City": "Bothey",
"Zip": "14394",
"ID": "65839483"
},
{
"First Name": "Christen",
"Last Name": "Hardin",
"Address": "390-1605 Adipiscing Street",
"City": "Oudergem",
"Zip": "90085",
"ID": "78046404"
},
{
"First Name": "Uma",
"Last Name": "Cunningham",
"Address": "313-1839 Lorem Av.",
"City": "San Cristóbal de la Laguna",
"Zip": "99153",
"ID": "27367690"
}
]
}
和JS to - &gt;
$.getJSON('SampleUserData.json', function(data) {
var output="<ul>";
$.each(data.result, function (index, val) {
output+="<li>" + String(val.ID) + " " + String(val['Last Name']) + "--" +"</li>";
});
output+="</ul>";
document.getElementById("placeholder").innerHTML=output;
});