ajax循环执行

//ajax执行批量操作
!function (w) {
  //ajax构造函数
  var ajaxConstructor = function (batchAjax, backCall) {
    this.run = false;
    this.isOk = false;
    this.backCall = backCall ? backCall : null;
    batchAjax.addajax(this);
  }
  ajaxConstructor.prototype.funok = function () {
    this.run = false;
    this.isOk = true;
  };
  ajaxConstructor.prototype.funrun = function (force) {
    var _self = this;
    if (force) {
      _self.isOk = false;//强制执行
    }
    if (_self.run || _self.isOk) {
      return;
    }
    _self.run = true;
    this.backCall(function () {
      _self.funok.call(_self);
    });
  };

  //批量操作ajax
  var batchAjax = function () {
    this.isOk = false;
    this.okNum = 0;
    this.ajaxLen = 0;
    this.ajaxArray = [];
    this.callBack;
  }
  batchAjax.prototype = {
    addajax: function (ajax) {
      this.ajaxArray.push(ajax);
    },
    ok: function () {
      var ajaxArrayItem = this.ajaxArray[this.okNum];
      ajaxArrayItem.run = false;
      ajaxArrayItem.isOk = true;
      this.okNum++;
      if (this.okNum >= this.ajaxLen && this.callBack) {
        this.callBack();
        return;
      }
      this.run();//goon
    },
    run: function (call) {
      var _slef = this;
      if (!this.ajaxLen) {
        this.ajaxLen = this.ajaxArray.length;
      }
      if (!this.callBack) {
        this.callBack = call;
      }
      if (this.ajaxLen) {
        var ajaxArrayItem = _slef.ajaxArray[_slef.okNum];
        ajaxArrayItem.run = true;
        //已执行了ajax且成功处理
        if (ajaxArrayItem.isOk) {
          _slef.ok.call(_slef);
          return;
        }
        //开始执行ajax
        ajaxArrayItem.backCall(function () {
          _slef.ok.call(_slef);
        });
      }
    },
    result: function () {
      if (this.okNum >= this.ajaxArray.length) {
        return true;
      }
    }
  }

  window.batchAjaxs = function (call, currBatchAjax) {
    var _batchAjax;
    if (currBatchAjax) {
      _batchAjax = currBatchAjax;
    }
    else {
      _batchAjax = new batchAjax();
    }
    return {
      batchAjax: _batchAjax,
      ajaxConstructor: new ajaxConstructor(_batchAjax, call)
    }
  };

}(window);

 

posted on 2016-07-29 17:17  流浪小白鼠  阅读(2321)  评论(0编辑  收藏  举报