开发者

How to take an action when all ajax calls in each loop success?

开发者 https://www.devze.com 2023-03-17 07:58 出处:网络
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.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消