使用JSON

Jac*_*nto 1 jquery json

我现在正在学习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"}
    ]
};
Run Code Online (Sandbox Code Playgroud)

然后代码会是这样的吗?

$(function() {
    $.getJSON('jsonFile.js',function(data){
        $.each(data, function(){
            console.log(header1.title);
            console.log(header2.title);
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

再次,我是JSON的新手,所以任何教程,建议,以及任何帮助我理解这里的核心概念的东西都会有所帮助.

jor*_*are 5

你的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"} 
    ] 
}
Run Code Online (Sandbox Code Playgroud)

你的代码:

$(function() {   
    $.getJSON('jsonFile.js',function(data){

        console.log(data.header1[0].title);   
        console.log(data.header2[0].title);     
    });   
});  
Run Code Online (Sandbox Code Playgroud)

(可选)在data.header1和data.header2上执行each()