How can I make batches of ajax requests in jQuery?

前端 未结 4 2057
半阙折子戏
半阙折子戏 2020-12-05 05:35

I\'m wondering how to make ajax calls in groups of n.

Here\'s my use case:

I have a table that displays usage data. You can drill into each row, and if eac

4条回答
  •  长情又很酷
    2020-12-05 06:04

    I agree with eicto: make your own message manager if you can't integrate another one. Here's my crack at a tiny one:

    var AjaxQueue = function(max) {
      this.max = max;
      this.requests = [];
      this.current = 0;
    }
    
    AjaxQueue.prototype.ajax = function(opts) {
      var queue = this;
      opts.complete = function(jqXHR, textStatus) {
        queue.current -= 1;
        queue.send();
      };
      this.requests.push(opts);
      this.send();
    }
    
    AjaxQueue.prototype.send = function(opts) {
      while (this.current < this.max && this.requests.length > 0) {
        $.ajax(this.requests.unshift());
        this.current += 1;
      }
    }
    

    I haven't tried using it yet, so there are bound to be bugs. Also it assumes you aren't using a complete option. It just overrides it. If you are you could check for it and make sure the previous complete function(s) still get called.

提交回复
热议问题