迭代多个json,而不仅仅是一个
Iterate over multiple JSONs instead of just one
我使用了一些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>");
});
});
})
相关文章:
- Ajax聊天消息重复而不仅仅是更新
- 鼠标悬停事件影响列表中所有行中的按钮,而不仅仅是特定按钮
- for 循环中的 if 语句都执行,而不仅仅是一个
- jQuery隐藏所有trs或td,而不仅仅是一个
- javascript 类“chzn-select”不仅仅是一个类名吗?
- 使用 querySelectorAll 获取具有该类名的所有元素,而不仅仅是第一个
- 将事件绑定到类中的所有元素,而不仅仅是一个 id
- 选择多个项目,而不仅仅是一个(angularJs)
- 我的Javascript正在切换所有元素,而不仅仅是一个元素
- 如何判断数组是否包含另一个特定数组,而不仅仅是其元素
- 有没有可能让GORM用一个空切片来填充nil值,而不仅仅是nil
- 获取一个完整的a标记,而不仅仅是href属性
- KnockoutJS正在更新数组中的所有对象,而不仅仅是一个对象
- 如何让我的点击每次都得到一个新的Ajax请求,而不仅仅是像以前一样使用相同的Ajax请求
- 迭代多个json,而不仅仅是一个
- 将整个元素插入到另一个元素中,而不仅仅是其内部HTML
- 我如何检测用户何时离开我的网站,而不仅仅是去到另一个页面
- JsHint,我可以在函数定义中针对所有未使用的参数,而不仅仅是最后一个
- 如何使键盘事件从整个文档触发,而不仅仅是一个按钮
- 模拟一个实际的右键,而不仅仅是鼠标向下或鼠标向上