我现在正在学习 json,为了让我的壮举发挥作用,可以这么说,我想知道获取包含 json 信息的文件并用它填充网站的最佳方法是什么。该文件将是这样的:
window.test =
{
"header1":
[
{ "title": "title1", "author": "author1"},
{ "title": "title2", "author": "author2"},
{ "title": "title3", "author": "author3"}
],
"header2":
[
{ "title": "title1", "author": "author1"},
{ "title": "title1", "author": "author2"},
{ "title": "title1", "author": "author3"}
]
};
那么代码会是这样吗?
$(function() {
$.getJSON('jsonFile.js',function(data){
$.each(data, function(){
console.log(header1.title);
console.log(header2.title);
});
});
});
我还是个 JSON 新手,所以任何教程、建议以及任何可以帮助我理解核心概念的东西都会有所帮助。
你的json:
{
"header1":
[
{ "title": "title1", "author": "author1"},
{ "title": "title2", "author": "author2"},
{ "title": "title3", "author": "author3"}
],
"header2":
[
{ "title": "title1", "author": "author1"},
{ "title": "title1", "author": "author2"},
{ "title": "title1", "author": "author3"}
]
}
您的代码:
$(function() {
$.getJSON('jsonFile.js',function(data){
console.log(data.header1[0].title);
console.log(data.header2[0].title);
});
});
(可选)对 data.header1 和 data.header2 执行each()
正如其他人所说,您应该删除
window.text
和结尾的分号。然后,当您像这样直接读取文件时,它将被编码为文本,因此您需要在迭代之前将其转换为 JSON。
您可以执行
var jsonData = JSON.parse(data));
从数据参数中获取JSON对象。
对于您拥有的 JSON 构造,如下所示的循环应该是正确的。
$.each(test, function(key, val) {
console.log(key); //this will print the header
$.each(val, function(index, val1) {
console.log(val1.title + ' ' + val1.author); //this will print the header contents
});
});