/*
@params
url: 请求的地址
pram: 发送的数据
method: 请求的方式
*/
var RequestArray = [], //存储请求的数组
argItem = [],
result = null,
xmlHttp = null;
function sendAjax(url, pram, method) {
AddRequestArray(url, pram, method);
}
function AddRequestArray(url, pram, method) {
var ArgItem = new Array();
ArgItem[0] = url;
ArgItem[1] = pram;
ArgItem[2] = method;
RequestArray.push(ArgItem); //将当前请求添加到队列末尾
if (RequestArray.length == 1) {
//如果请求队列里只有当前请求立即要求执行队列,如果有其他请求,那么就不要求执行队列
ExeRequest();
}
}
//开始执行一个ajax请求
function ExeRequest() {
var arr = RequestArray[0];
startRequest(arr[0], arr[1], arr[2]);
}
function createXMLHttpRequest() {
if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
}
/*发送请求
@param
url: 请求的地址
pram: 发送的数据
re_mod: 请求的方式
*/
function startRequest(url, param, re_mod) {
xmlHttp = createXMLHttpRequest();
var xmlobj = this; //把本对象赋值给一个变量是为了兼容ie因为this对象在不同的浏览器中有不同的解释
xmlobj.xmlHttp.onreadystatechange = function () {
if (xmlobj.xmlHttp.readyState == 4) {
xmlobj.result = xmlobj.xmlHttp.responseText;
if (xmlobj.xmlHttp.status == 200 || xmlobj.xmlHttp.status == 500) {
uploadFile(0); //成功后可以调用其他函数
} else {
console.user-logout("error: " + xmlobj.result);
}
xmlobj.RequestArray.shift(); //移除队列里的顺序第一个的请求,即当前已经执行完成的请求
if (xmlobj.RequestArray.length >= 1) {
//如果请求队列里只有当前请求立即要求执行队列,如果有其他请求,那么就不要求执行队列
xmlobj.ExeRequest(); //要求执行队列中的请求
}
}
};
xmlobj.xmlHttp.open(re_mod, url, true);
xmlobj.xmlHttp.upload.onprogress = function (progress) {
updateProgress(progress); //可以获得进度条
};
console.log(RequestArray[0]);
argItem[3] = xmlobj.xmlHttp; //把请求存进数组,可以中止请求:argItem[3].abort()
xmlobj.xmlHttp.send(param);
}
//测试
sendAjax("http://localhost:9090/upload", form_data, "POST");
setTimeout(function(){
RequestArray[0][3].abort(); //1s后中止该请求
},1000);
可以把每一次请求存入数组中,根据索引排队执行,具体实现可以根据这段代码来。
如果用ajax的写法存入请求的话:
function startRequest(url, param, re_mod) {
$.ajax({
url: url,
data: param,
type: re_mod,
cache: false,
processData: false,
contentType: false, //必须false才会自动加上正确的Content-Type
//这里我们先拿到jQuery产生的 XMLHttpRequest对象,为其增加 progress 事件绑定,然后再返回交给ajax使用
xhr: function () {
let xhr = $.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.onprogress = function (progress) {
updateProgress(progress);
};
}
argItem[3] = xhr; //将每个上传任务的每一片存入requestObj对象中,该对象存入的是request_arr数组中,argItem[3].abort()
return xhr;
},
success: function(data)
{
if(data){
uploadFile(0); //这里只写成功后要调用的函数,排队请求的话可以把目前的startRequest函数放入要执行的排队请求的其他函数中,便于传递索引,而这个startRequest函数只具备执行单个请求的功能
}
else{
alert("error");
return false;
}
}
});
}
主要参考链接:https://www.zhaokeli.com/article/1511.html