等到所有 jQuery Ajax 请求都完成?

2022-01-29 00:00:00 jquery javascript ajax

如何让一个函数等到所有 jQuery Ajax 请求都在另一个函数中完成?

How do I make a function wait until all jQuery Ajax requests are done inside another function?

简而言之,在执行下一个请求之前,我需要等待所有 Ajax 请求完成.但是怎么做呢?

In short, I need to wait for all Ajax requests to be done before I execute the next. But how?

推荐答案

jQuery 现在定义了一个 when 函数 为此目的.

jQuery now defines a when function for this purpose.

它接受任意数量的 Deferred 对象作为参数,并在它们全部解析时执行一个函数.

It accepts any number of Deferred objects as arguments, and executes a function when all of them resolve.

这意味着,如果你想发起(例如)四个 ajax 请求,然后在它们完成后执行一个操作,你可以这样做:

That means, if you want to initiate (for example) four ajax requests, then perform an action when they are done, you could do something like this:

$.when(ajax1(), ajax2(), ajax3(), ajax4()).done(function(a1, a2, a3, a4){
    // the code here will be executed when all four ajax requests resolve.
    // a1, a2, a3 and a4 are lists of length 3 containing the response text,
    // status, and jqXHR object for each of the four ajax calls respectively.
});

function ajax1() {
    // NOTE:  This function must return the value 
    //        from calling the $.ajax() method.
    return $.ajax({
        url: "someUrl",
        dataType: "json",
        data:  yourJsonData,            
        ...
    });
}

在我看来,它提供了一种简洁明了的语法,并且避免了涉及任何全局变量,例如 ajaxStart 和 ajaxStop,这可能会在您的页面开发过程中产生不必要的副作用.

In my opinion, it makes for a clean and clear syntax, and avoids involving any global variables such as ajaxStart and ajaxStop, which could have unwanted side effects as your page develops.

如果您事先不知道需要等待多少个 ajax 参数(即您想使用可变数量的参数),它仍然可以完成,但有点棘手.请参阅 将延迟数组传递给 $.when()(可能还有 jQuery .当使用可变数量的参数进行故障排除时).

If you don't know in advance how many ajax arguments you need to wait for (i.e. you want to use a variable number of arguments), it can still be done but is just a little bit trickier. See Pass in an array of Deferreds to $.when() (and maybe jQuery .when troubleshooting with variable number of arguments).

如果您需要更深入地控制 ajax 脚本等的失败模式,您可以保存 .when() 返回的对象 - 它是一个 jQuery Promise 对象包含所有原始 ajax 查询.您可以在其上调用 .then().fail() 以添加详细的成功/失败处理程序.

If you need deeper control over the failure modes of the ajax scripts etc., you can save the object returned by .when() - it's a jQuery Promise object encompassing all of the original ajax queries. You can call .then() or .fail() on it to add detailed success/failure handlers.

相关文章