I call ajax jquery function inside .each loop, and I want to do an action just when all the ajax calls inside the loop finish and success.
$(".che开发者_StackOverflow中文版cked-box").each(function () {
// ajax call goes here
});
$('.messsage').html('all requests done');
How to do that? without async: false
because this blocks the browser.
Deferreds can make your work simpler.
var deferreds = $('.checked-box').map(function(i, elem) {
return $.ajax(params);
});
$.when.apply(null, deferreds.get()).then(function() { ... });
Hope this should work.
The concept is
$.when(
$.ajax( "1" ),
$.ajax( "2" ),
$.ajax( "3" )
).then( successFunc, failureFunc );
This is one way:
var numberOfPendingRequests = 8;
$(".checked-box").each(function () {
$.ajax({
success: function(){
...
numberOfPendingRequests --;
if(numberOfPendingRequests == 0) allDone();
}
});
});
function allDone(){
$('.messsage').html('all requests done');
}
You can calculate the initial numberOfPendingRequests
based on your number of checkboxes or start it at 0 an increment it before each ajax request, but this is the general idea.
Hope this helps. Cheers
Try this:
AjaxRequestCount = 0;
//JUST prepare ajax requests here, do not send yet...
$(".checked-box").each(function () {
AjaxRequestCount += 1; //Count number of ajax request
//set "success:" of each ajax to Success() function
});
//Send ajax requests here, use a loop...
for(i=0;i<AjaxRequestCount;i++)
{
//ajax[i].send
}
//Fires for each ajax success...
function Success()
{
SuccessAjaxRequestCount += 1;
Check(); //Check right after each ajax success
}
//Checks if already reached the expected number of ajax success...
function Check()
{
if(SuccessAjaxRequestCount == AjaxRequestCount )
{
alert("done!");
}
}
look at section 3.1 of this post for a complete example of waiting for asynchronous stuff to end
精彩评论