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

前端 未结 4 899
情书的邮戳
情书的邮戳 2020-12-09 07:18

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.

$(\".checked-box\"         


        
相关标签:
4条回答
  • 2020-12-09 07:41

    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!");
        }
    }
    
    0 讨论(0)
  • 2020-12-09 07:45

    look at section 3.1 of this post for a complete example of waiting for asynchronous stuff to end

    0 讨论(0)
  • 2020-12-09 07:52

    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 );
    
    0 讨论(0)
  • 2020-12-09 07:56

    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

    0 讨论(0)
提交回复
热议问题