使用AJAX检索嵌套的JSON数组并输出到HTML列表

时间:2019-02-15 19:18:00

标签: javascript arrays json ajax

这个想法是采用一个JSON数组,遍历planets的每个条目,并将它们输出到一个无序列表,每个li一个条目。在这种情况下,一切都很好。

当JavaScript文件包含JSON数组及其下面的代码时,我已经成功编写了一种输出嵌套JSON的方法,但是我很难确定从外部.json文件中检索相同数据的方法,使用AJAX。

这是有效的本地版本。

<ul id="object-list"></ul>
$(document).ready( function() {
    var sol_sys = [];
    sol_sys = {
        "stars": [
            { "name": "Sun", "object": "Star", "url": "stars/sun" }
        ],
        "planets": [
            { "name": "Mercury", "object": "Planet", "parent": "Sun", "url": "planets/mercury" },
            { "name": "Venus", "object": "Planet", "parent": "Sun", "url": "planets/venus" },
            { "name": "Earth", "object": "Planet", "parent": "Sun", "url": "planets/earth" },
            { "name": "Mars", "object": "Planet", "parent": "Sun", "url": "planets/mars" },
            { "name": "Ceres", "object": "Dwarf Planet", "parent": "Sun", "url": "planets/ceres" },
            { "name": "Jupiter", "object": "Planet", "parent": "Sun", "url": "planets/jupiter" },
            { "name": "Saturn", "object": "Planet", "parent": "Sun", "url": "planets/saturn" },
            { "name": "Uranus", "object": "Planet", "parent": "Sun", "url": "planets/uranus" },
            { "name": "Neptune", "object": "Planet", "parent": "Sun", "url": "planets/neptune" },
            { "name": "Pluto", "object": "Dwarf Planet", "parent": "Sun", "url": "planets/pluto" },
            { "name": "Eris", "object": "Dwarf Planet", "parent": "Sun", "url": "planets/eris" }
        ],
        "moons": [
            { "name": "Luna", "object": "Moon", "parent": "Earth", "url": "moons/luna" },
            { "name": "Callisto", "object": "Moon", "parent": "Jupiter", "url": "moons/callisto" },
            { "name": "Ganymede", "object": "Moon", "parent": "Jupiter", "url": "moons/ganymede" },
            { "name": "Io", "object": "Moon", "parent": "Jupiter", "url": "moons/io" },
            { "name": "Europa", "object": "Moon", "parent": "Jupiter", "url": "moons/europa" },
            { "name": "Enceladus", "object": "Moon", "parent": "Saturn", "url": "moons/enceladus" },
            { "name": "Titan", "object": "Moon", "parent": "Saturn", "url": "moons/titan" },
            { "name": "Miranda", "object": "Moon", "parent": "Uranus", "url": "moons/miranda" },
            { "name": "Triton", "object": "Moon", "parent": "Neptune", "url": "moons/triton" },
            { "name": "Charon", "object": "Moon", "parent": "Pluto", "url": "moons/charon" }
        ]
    }

    var x = [];
    $.each(sol_sys.planets, function(index) {
        x += '<li><a href="' + sol_sys.planets[index].url + '" title="' + sol_sys.planets[index].name + '" target="_blank">' + sol_sys.planets[index].name + '</a></li>';
    });
    $('#object-list').append(x);
});

但是,我花了两天的时间来弄清楚实现此目的的方法,将JSON放在单独的.json文件中。

以下是我尝试的一种方法的示例:

$(document).ready( function() {
    var sol_sys = $.getJSON('assets/data.json');
    var x = [];

    $.each(sol_sys.planets, function(index) {
        x += '<li><a href="' + sol_sys.planets[index].url + '" title="' + sol_sys.planets[index].name + '" target="_blank">' + sol_sys.planets[index].name + '</a></li>';
    });
    $('#object-list').append(x);
});

此代码成功获取了数据,如在控制台中所见,但它还会显示以下错误消息: Uncaught TypeError: Cannot read property 'length' of undefined

我认为我完全错过了一些明显的东西。我还尝试了演示here的方法,其结果完全相同。

有人能指出我正确的方向吗?

谢谢!

2 个答案:

答案 0 :(得分:2)

$.getJSON是一个异步调用-因此您需要使用回调函数来访问返回的数据:

$.getJSON('assets/data.json', function(sol_sys) {
    var x = [];

    $.each(sol_sys.planets, function(index) {
        x += '<li><a href="' + sol_sys.planets[index].url + '" title="' + sol_sys.planets[index].name + '" target="_blank">' + sol_sys.planets[index].name + '</a></li>';
    });
    $('#object-list').append(x);
});

答案 1 :(得分:1)

嗨,你可以这样:

您的ajax:

function getList() {
   return $.ajax({
        type: "GET",
        url: "YourUrl"
    })

}

这样称呼它:

    getList().done(function(response){
    var data=JSON.parse(response);
    if (data != null) {
    jQuery.each(data, function(index, value){
//use an id in your ul in order to append some items
    $("#yourUl id").append('<li><a href=' + value.url+ '>' + value.name+ '</a></li>');
                                                    });
        }

})

$.getJSON( 'assets/data.json').done(function(response) {
    var data=JSON.parse(response);
    if (data != null) {
    jQuery.each(data, function(index, value){
    //use an id in your ul in order to append some items
    $("#yourUl id").append('<li><a href=' + value.url+ '>' + value.name+ '</a></li>');
});
}
})

编辑:附加如下元素:

        $.getJSON( 'data.json').done(function(response) {
    jQuery.each(response, function(index, value){
    $("#planetList").append('<li>'+index+'</li>');
     jQuery.each(value, function(index2, value2){
    $("#planetList").append('<ul><li><a href=' +value2.url+ '>' +value2.name+ '</a></li>')
    console.log(value2);
     })
         $("#planetList").append('<ul>');
    })
})

希望有帮助