jQuery Multiple getJSON requests

前端 未结 2 1824
孤城傲影
孤城傲影 2020-12-28 10:47

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.

My problem is

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-28 11:39

    Using jQuery 1.5 deferred objects:

    Accumulate an array of the JQXHR objects returned by $.getJSON()

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

    and only $.when they're all .done():

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

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

提交回复
热议问题