使用 jQuery 读取 JSON 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10936196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read JSON File with jQuery
提问by Rafael Marques
Hey I'm trying to read data from a JSON File with jQuery. This is my JS:
嘿,我正在尝试使用 jQuery 从 JSON 文件中读取数据。这是我的JS:
$(document).ready(function() {
var myItems;
$.getJSON('testData.json', function(data) {
myItems = data.items;
console.log(myItems);
});
});
And that is the JSON File:
这就是 JSON 文件:
{"fname":"rafael","lname":"marques","age":"19"}
{"fname":"daniel","lname":"marques","age":"19"}
When I open my HTML Page in the Browser I can't see nothing in the Console.
当我在浏览器中打开我的 HTML 页面时,我在控制台中什么也看不到。
回答by thecodeparadox
Add comma after each object, wrap then with []
and enclosed them with an object with property items
in json file so it will look like
在每个对象后添加逗号,然后用[]
包裹并用items
json 文件中具有属性的对象将它们括起来,因此它看起来像
{
items: [
{
"fname": "rafael",
"lname": "marques",
"age": "19"},
{
"fname": "daniel",
"lname": "marques",
"age": "19"
}]
}
then you should try for
那么你应该尝试
$.each(data.items, function(key, val) {
alert(val.fname);
alert(val.lname);
})
回答by Denys Séguret
{"fname":"rafael","lname":"marques","age":"19"}
{"fname":"daniel","lname":"marques","age":"19"}
Isn't a correct json file. Add a comma between the lines or make it like this :
不是正确的 json 文件。在两行之间添加一个逗号或使其像这样:
{items:[
{"fname":"rafael","lname":"marques","age":"19"},
{"fname":"daniel","lname":"marques","age":"19"}
]}
to comply with your apparent requirements.
符合您的明显要求。
But opening the console to look at errors would have solved this.
但是打开控制台查看错误就可以解决这个问题。