javascript - 迭代多个 JSON 而不是仅一个

标签 javascript jquery json

我有一些 jQuery,可以迭代一些 JSON(特别是 Google 日历提要)并打印日历中每个事件的列表项。代码如下所示:

// 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>");
        });
    });
})

关于javascript - 迭代多个 JSON 而不是仅一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24378220/

相关文章:

c# - 扩展 CamelCasePropertyNamesContractResolver 不起作用

javascript - 是否可以仅在第一次运行时调用函数?

javascript - lodash 中的多个版本的 keyBy? (组值共享一个键作为一个数组)

Javascript - 如何停止缩放、多点触控输入攻击?

php - Laravel 连接 2 个表,第一个表中的一个数据和第二个表中的多行

php - 通过 JSON 将分隔字符串发送到 PHP 以获取准备好的语句

javascript - 如何让 ng-disabled 检查 ng-repeat 中的项目值(使用 AngularJS)

javascript - 如何创建用下面的内容展开的按钮

PHP AJAX 处理程序文件组织

javascript - 是什么原因导致 datepicker 无法使用 jquery 在 rails 3.1.3 中加载?