史上最牛的原生js实现ajax

5 篇文章 0 订阅
5 篇文章 0 订阅

废话不多说,直接上代码:

let ajaxRequest = function ({
                                    url,
                                    method = 'GET',
                                    dataType = 'text',
                                    data = null,
                                    success = null,
                                    fail = null,
                                    completed = null,
                                    async = true,
                                    header = {},
                                }) {


        method = method.toLocaleUpperCase();
        dataType = dataType.toLocaleLowerCase();

        function createXHR() {
            if (typeof XMLHttpRequest != "undefined") {
                return new XMLHttpRequest();
            } else if (typeof ActiveXObject != "undefined") {
                if (typeof arguments.callee.activeXString != "string") {
                    var versions = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp"], i, len;
                    for (i = 0, len = versions.length; i < len; i++) {
                        try {
                            new ActiveXObject(versions[i]);
                            arguments.callee.activeXString = versions[i];
                            break;
                        } catch (ex) {
                            //跳过
                        }
                    }
                }
                return new ActiveXObject(arguments.callee.activeXString);
            } else {
                throw new Error("No XHR object available.");
            }
        }

        function makeParams(data, name_prefix = '') {
            let paramsStr = '', prefix = '';
            if (typeof data == 'object') {
                for (var name in data) {
                    var value = data[name];
                    if (typeof value == 'object') {
                        if (name_prefix) {
                            prefix += '[' + name + ']';
                        } else {
                            prefix = name;
                        }
                        paramsStr += makeParams(value, name_prefix + prefix);
                    } else {
                        if (name_prefix) {
                            name = name_prefix + '[' + name + ']';
                        }
                        paramsStr += encodeURIComponent(name) + "=" + encodeURIComponent(value) + "&";
                    }
                }
            } else {
                paramsStr += data;
            }

            return paramsStr;
        }

        function addURLParam(url, data) {
            url += (url.indexOf("?") == -1 ? "?" : "&");
            url += makeParams(data);
            url = url.replace(/((\s*&\s*)|(\s*?\s*))$/g, '');
            return url;
        }

        this.xhr = createXHR();
        this.xhr.onreadystatechange = () => {
            console.log(this.xhr.readyState, this.xhr.statusText)
            if (this.xhr.readyState == 4) {
                let rst = this.xhr.responseText;
                if ((this.xhr.status >= 200 && this.xhr.status < 300) || this.xhr.status == 304) {
                    switch (dataType) {
                        case 'json':
                            rst = JSON.parse(rst);
                            break;
                        case 'text':
                        default:
                    }
                    if (success) {
                        success(rst, this.xhr);
                    }
                } else {
                    rst = new Error(this.xhr.statusText);
                    if (fail) {
                        fail(rst, this.xhr);
                    }
                }
                if (completed) completed(rst, this.xhr);
            }
        };
        this.xhr.withCredentials = true; // session同步问题
        switch (method) {
            case 'POST':
                data = makeParams(data);
                this.xhr.open(method, url, async);
                this.xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
                break;
            default:
                if (data && Object.keys(data).length) {
                    url = addURLParam(url, data);
                }
                this.xhr.open(method, url, async);
                data = null;
        }
        // 设置请求头
        if (Object.keys(header).length) {
            for (var name in header) {
                this.xhr.setRequestHeader(name, header[name]);
            }
        }
        this.xhr.send(data);
    };

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值