迭代多个json,而不仅仅是一个

Iterate over multiple JSONs instead of just one

本文关键字:不仅仅是 一个 json 迭代      更新时间:2023-09-26

我使用了一些jQuery来迭代一些JSON(特别是Google Calendar提要),并为日历中的每个事件打印出一个列表项。代码看起来像这样:

// URL for some Google Calendar data
// (if this link should go down, any gcal feed URL should work just the same)
var gcalUrl = "http://mikeclaffey.com/sandbox/gcal-embed/example-json-data.js";
// Get list of upcoming events formatted in JSON
$.getJSON(gcalUrl, function(data){
    // Parse and render each event
    $.each(data.feed.entry, function(i, item){
        // Render the event
        $("#gcal-events li").last().after( "<li>" + item.title.$t + "</li>" );
    });
});

我正试图调整代码,以便它可以从多个url组合JSON,但我有麻烦将JSON数据组合成一个对象。我尝试遍历JSON url数组并将所有数据组合成一个对象,但它似乎没有创建一个可用的对象。下面是我的代码:

var gcalUrls = ["http://mikeclaffey.com/sandbox/gcal-embed/example-json-data.js"];
var allData = {};
// Iterate through the array of Google Calendar feed URLs
$.each(gcalUrls, function(i, url) {
    // Download each feed
    $.getJSON(url, function(data){
        // Add this feed's data to allData
        $.extend(true, allData, data);
    });
});
// Parse and render each event
$.each(data.feed.entry, function(i, item){
    // Render the event
    $("#gcal-events li").last().after( "<li>" + item.title.$t + "</li>" );
});

这段代码没有打印出任何东西。我做错了什么?

由于ajax的异步特性,它无法工作。

你可以像

那样使用$.when()来解决它
var gcalUrls = ["http://mikeclaffey.com/sandbox/gcal-embed/example-json-data.js"];
var allData = {};
// Iterate through the array of Google Calendar feed URLs
var promises = $.map(gcalUrls, function (i, url) {
    // Download each feed
    return $.getJSON(url);
});
$.when.apply($, promises).then(function () {
    // Parse and render each event
    $.each(arguments, function (i, arg) {
        // Parse and render each event
        $.each(arg[0].feed.entry, function (i, item) {
            // Render the event
            $("#gcal-events li").last().after("<li>" + item.title.$t + "</li>");
        });
    });
})