等到所有的jQuery的Ajax请求都做了什么? [英] Wait until all jQuery Ajax requests are done?
问题描述
我如何做一个函数等待,直到所有的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的定义了一个何时功能,用于这一目的。
Actually, jQuery now defines a 'when' function for this purpose.
http://api.jquery.com/jQuery.when/
它接受任何数目的延迟对象作为参数,并执行在所有这些解决功能。
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的参数(例如,你想使用可变数量的参数),它仍然可以做,但只是一点点麻烦。请参见通在Deferreds至$。当()(也许<一个数组href="http://stackoverflow.com/questions/9865586/jquery-when-troubleshooting-with-variable-number-of-arguments">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脚本等故障模式,您可以通过保存。当()返回的对象 - 这是一个jQuery的无极对象包括所有原AJAX查询。你可以调用。那么()或.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请求都做了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!