jQuery多个getJSON请求 [英] jQuery Multiple getJSON requests

查看:63
本文介绍了jQuery多个getJSON请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的脚本需要在 https://graph.facebook.com/xxxx 上获取几个json文件,并从每个json中检索某个字段,然后计算总和。

My script needs to fetch several json files on https://graph.facebook.com/xxxx, and retrieve a certain field from each json, then calculate summation.

我的问题是如何在所有getJSON完成后打印出结果?使用以下代码,它将打印0.随意建议任何更好的方法。

My problem is how to print out the result after all getJSON done? With below code it will prints 0. Feel free to suggest any better approaches.

var result = 0;
$.each(urls, function (i, url) {
    $.getJSON(url, function (json) {
        result += json.field1;
    })
});
alert(result);


推荐答案

使用jQuery 1.5延迟对象:

Using jQuery 1.5 deferred objects:

累积由 $返回的JQXHR对象数组.getJSON()

var jxhr = urls.map(function(url) {
    return $.getJSON(url, function(json) {
        result += json.field1;
    })
});

且只有 $。当他们是所有 .done()

$.when.apply($, jxhr).done(function() {
    alert(result);
});

注意:这将累积结果命令AJAX调用完成,而不是按照它们的顺序。

NB: this will accumulate result in the order that the AJAX calls complete, not in the order they're made.

这篇关于jQuery多个getJSON请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆