javascript - Iterate over multiple JSONs instead of just one -
i have bit of jquery iterates through json (specifically google calendar feed) , prints out list item each event in calendar. code looks this:
// url google calendar info // (if link should go down, gcal feed url should work same) var gcalurl = "http://mikeclaffey.com/sandbox/gcal-embed/example-json-data.js"; // list of upcoming events formatted in json $.getjson(gcalurl, function(data){ // parse , render each event $.each(data.feed.entry, function(i, item){ // render event $("#gcal-events li").last().after( "<li>" + item.title.$t + "</li>" ); }); }); i trying adapt code can combine json multiple urls, i'm having problem combining json info 1 object. tried iterating through array of json urls , combining info 1 object, doesn't seem create usable object. here's code:
var gcalurls = ["http://mikeclaffey.com/sandbox/gcal-embed/example-json-data.js"]; var alldata = {}; // iterate through array of google calendar feed urls $.each(gcalurls, function(i, url) { // download each feed $.getjson(url, function(data){ // add together feed's info alldata $.extend(true, alldata, data); }); }); // parse , render each event $.each(data.feed.entry, function(i, item){ // render event $("#gcal-events li").last().after( "<li>" + item.title.$t + "</li>" ); }); this code fails print out anything. doing wrong?
it won't work because of async nature of ajax.
you can utilize $.when() solve like
var gcalurls = ["http://mikeclaffey.com/sandbox/gcal-embed/example-json-data.js"]; var alldata = {}; // iterate through array of google calendar feed urls var promises = $.map(gcalurls, function (i, url) { // download each feed homecoming $.getjson(url); }); $.when.apply($, promises).then(function () { // parse , render each event $.each(arguments, function (i, arg) { // parse , render each event $.each(arg[0].feed.entry, function (i, item) { // render event $("#gcal-events li").last().after("<li>" + item.title.$t + "</li>"); }); }); }) javascript jquery json
No comments:
Post a Comment