Wait until all jQuery Ajax requests are done?

后端 未结 21 1784
离开以前
离开以前 2020-11-21 04:39

How do I make a function wait until all jQuery Ajax requests are done inside another function?

In short, I need to wait for all Ajax requests to be done before I exe

21条回答
  •  渐次进展
    2020-11-21 05:37

    I found a good answer by gnarf my self which is exactly what I was looking for :)

    jQuery ajaxQueue

    //This handles the queues    
    (function($) {
    
      var ajaxQueue = $({});
    
      $.ajaxQueue = function(ajaxOpts) {
    
        var oldComplete = ajaxOpts.complete;
    
        ajaxQueue.queue(function(next) {
    
          ajaxOpts.complete = function() {
            if (oldComplete) oldComplete.apply(this, arguments);
    
            next();
          };
    
          $.ajax(ajaxOpts);
        });
      };
    
    })(jQuery);
    

    Then you can add a ajax request to the queue like this:

    $.ajaxQueue({
            url: 'page.php',
            data: {id: 1},
            type: 'POST',
            success: function(data) {
                $('#status').html(data);
            }
        });
    

提交回复
热议问题