我有一些 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/