如何使ajax请求按顺序执行

最近在公司遇到了一个难点,就是公司的上传接口,如果两个文件同时上传,也就是同时调用这个接口,那么就会报错,然后我就发现了,一个一个挨着调用不会报错,也就是说上一个请求完事了,下一个请求接着上,就没事,我苦思冥想,再加上百度一下。。。终于搞出来了,有两种方案,我选择的第二种,第一种也记录一下

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;

今天的笔记就先做到这里吧,哈哈哈!

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值