how to call a function after a set of multiple ajax request complete on jquery?
I am calling multiple ajax requests at a time. I have a single function which calls the server and gets the response and processes it. Based on the parameters passed to it, I will decide what to be returned on the server side.
I want to call a function once all the ajax requests are complete as each would take different timespan depending on various aspects.
I tied jQuery http://api.jquery.com/jQuery.when/ but the function in the .then()
gets called immediately.
Here is what I tried :
$.when(GetAjaxData(someUrl1), GetAjaxData(someUrl2), GetAjaxData(someUrl3)).then(alert("done"), alert("not done"));
is there any other approach that you can think of?
Little known fact, $.when() will execute the then() callback immediately if any one of the parameters fails. To quote the documentation:
http://api.jquery.com/jQuery.when/
In the multiple-Deferreds case where one of the Deferreds is rejected, jQuery.when immediately fires the failCallbacks for its master Deferred. Note that some of the Deferreds may still be unresolved at that point. If you need to perform additional processing for this case, such as canceling any unfinished ajax requests, you can keep references to the underlying jqXHR objects in a closure and inspect/cancel them in the failCallback.
There's actually no built-in way of waiting until all of them are finished regardless of their success/failure status.
So, I built a $.whenAll() for you :)
http://jsfiddle.net/InfinitiesLoop/yQsYK/
jQuery.when
only works when a jQuery.Deferred
object is returned, so in your GetAjaxData
function, you want to return the jqXHR object (which is a Deferred).
Something like this:
function GetAjaxData(url) {
return $.ajax({
url: url,
... more options
})
}
This will execute the AJAX request and return the jqXHR object, which jQuery.when
knows how to use.
You want deferred.always():
// Called when all deferreds are either resolved or rejected
$.when(
$.ajax("/page1.php"),
$.ajax("/page2.php"),
$.ajax("/page3.php"))
.always(function() { alert("AJAX requests completed") });
$(document).ajaxStop(function () {
// or call the function which you want to call after all the ajax calls
});
精彩评论