实现ajax的队列请求

var ajaxes = []; //用于存储参数对象的队列  
//用于声明XMLHttpRequest实例对象  
var Xhr = function(){  
  var xhr = false;  
  try {  
    xhr = new XMLHttpRequest();  
  }  
  catch (e) {  
    try {  
      xhr = new ActiveXObject("Msxml2.XMLHTTP");  
    }  
    catch (e) {  
      xhr = new ActiveXObject("Microsoft.XMLHTTP");  
    }  
  }  
  return xhr;  
}  
var xhr = new Xhr(); //获得XMLHttpRequest实例对象xhr  
//executeAjax是主要的执行Ajax的函数  
var executeAjax = function(){  
  //如果队列为空,则退出执行  
  if (!ajaxes.length)  
  return;  
  var options = ajaxes[0];  
  if (xhr) {  
    xhr.open(options.method, options.url, true);  
    xhr.onreadystatechange = function(){  
      if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 304)) {  
        options.callback(xhr.responseText, xhr);  
        //删除队列中的第一个请求  
        ajaxes.shift();  
        //如果队列中还有请求,就接着递归执行executeAjax函数,直到队列为空  
        if (ajaxes.length > 0) {  
          executeAjax();  
        }  
      }  
    }  
    if (xhr.method === "post") {  
      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    }  
    xhr.send(options.data || null);  
  }  
}  
//用于添加队列的函数  
var addAjax = function(options){  
  ajaxes.push(options);  

}  


实现方法:

 1、创建一个队列数组[]

 2、将所有的请求push到队列数组

 3、请求队列数组(清空队列)

猜你喜欢

转载自blog.csdn.net/qq_26775359/article/details/78788822