如何让一个函数等到所有 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 .when 使用可变数量的参数进行故障排除).
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.
更多推荐
等到所有 jQuery Ajax 请求完成?
发布评论