Wait for multiple getJSON calls to finish

女生的网名这么多〃 提交于 2019-11-28 22:11:13

This is easy if you use jQuery's deferreds. There is a method, $.when, that waits for multiple promises to complete then runs a callback. That's what you should use here.

Don't use a global obj variable, you can just use the returns from the AJAX calls.

function getData(id) {
    var thisI = i;
    var url = "www.whatever.com?id=" + id;
    return $.getJSON(url);  // this returns a "promise"
}

So, instead of populating obj, we just return the promise. Then in your loop, you collect all of them.

var AJAX = [];
for (i=0; i < ids.length; i++) {
    AJAX.push(getData(ids[i]));
}

Then we need to hook up the callback when all of them are done:

$.when.apply($, AJAX).done(function(){
    // This callback will be called with multiple arguments,
    // one for each AJAX call
    // Each argument is an array with the following structure: [data, statusText, jqXHR]

    // Let's map the arguments into an object, for ease of use
    var obj = [];
    for(var i = 0, len = arguments.length; i < len; i++){
        obj.push(arguments[i][0]);
    }

    document.getElementById("txt").innerHTML = obj[0]['field'];
});

getData will return a promise which is a read-only version of a deferred. You can then execute code based on the resolution of these promises using $.when

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!