最近在公司遇到了一个难点,就是公司的上传接口,如果两个文件同时上传,也就是同时调用这个接口,那么就会报错,然后我就发现了,一个一个挨着调用不会报错,也就是说上一个请求完事了,下一个请求接着上,就没事,我苦思冥想,再加上百度一下。。。终于搞出来了,有两种方案,我选择的第二种,第一种也记录一下
1.将ajax封装成同步请求,代码如下所示
// 同步请求的方法
export const syncHttp = (config) => {
var tokenStr = localStorage.getItem('tokenStr');
const xhrConifg = {
method: 'get',
url: '',
data: {},
onUploadProgress: () => { },
success: () => { },
error: () => { },
...config
}
if (xhrConifg.method == 'get' && JSON.stringify(xhrConifg.data) != '{}') {
let params = '?';
for (let key in xhrConifg.data) {
params += key + '=' + xhrConifg.data[key] + '&'
}
params = params.slice(0, -1);
xhrConifg.url += params;
}
let xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", function (e) {
xhrConifg.onUploadProgress(e);
})
xhr.open(xhrConifg.method, xhrConifg.url, false);
xhr.setRequestHeader("Authorization", tokenStr);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
xhrConifg.success(xhr.responseText);
} else {
xhrConifg.error(xhr.responseText);
}
};
xhr.send(xhrConifg.data)
}
重点来了,第二种方式
2. 将ajax请求一个一个先push到数组里,再一个一个递归执行
// 创建 XMLHttpRequest实例对象
function Xhr() {
this.xhr = null;
this.ajaxArray = [];
this.currentAjaxArrayIndex = undefined;
try {
this.xhr = new XMLHttpRequest();
}
catch (e) {
try {
this.xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
this.xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
};
Xhr.prototype.addAjax = function (option) {
this.ajaxArray.push(option);
};
Xhr.prototype.runAjax = function (resultCallback) {
var option = this.ajaxArray[this.currentAjaxArrayIndex];
var tokenStr = localStorage.getItem('tokenStr');
if (!option) {
return;
}
if (this.xhr) {
if (option.method == 'get' && JSON.stringify(option.data) != '{}') {
let params = '?';
for (let key in option.data) {
params += key + '=' + option.data[key] + '&'
}
params = params.slice(0, -1);
option.url += params;
}
this.xhr.open(option.method, option.url, true);
this.xhr.setRequestHeader("Authorization", tokenStr);
this.xhr.onreadystatechange = () => {
if (this.xhr.readyState === 4 && (this.xhr.status === 200 || this.xhr.status === 304)) {
//执行回调方法
if (option.callback) {
option.callback(this.xhr.responseText)
}
// 如果队列中还有未执行的请求,就接着递归执行executeAjax函数,最后一个请求;
if (this.currentAjaxArrayIndex < this.ajaxArray.length - 1) {
this.currentAjaxArrayIndex++;
this.runAjax(resultCallback);
} else {
this.currentAjaxArrayIndex = 0;
this.ajaxArray = [];
if (resultCallback) {
resultCallback();
}
}
}
};
this.xhr.send(option.data || null);
}
};
export default Xhr;
今天的笔记就先做到这里吧,哈哈哈!