原生ajax封装

        //原生aj
        ajax(options) {
            options = options || {};
            options.type = (options.type || "GET").toUpperCase();
            options.dataType = options.dataType || "json";
            //创建xhr对象 - 非IE6
            if (window.XMLHttpRequest) {
                var xhr = new XMLHttpRequest();
            } else { //IE6及其以下版本浏览器
                var xhr = new ActiveXObject('Microsoft.XMLHTTP');
            }
            xhr.timeout = 30000;
            xhr.ontimeout = function(event) {
                alert('请求超时!');
            }
            var params;
            //GET POST 两种请求方式
            if (options.type == "GET") {
                params = this.formatParams(options.data);
                xhr.open("GET", options.url + "?" + params, true);
                xhr.send(null);
            } else if (options.type == "POST") {
                if (options.data instanceof FormData) {
                    xhr.open("POST", options.url, true);
                    params = options.data;
                } else {
                    xhr.open("POST", options.url, true);
                    params = this.formatParams(options.data);
                    // params = options.data;
                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                }
                //设置表单提交时的内容类型
                // xhr.setRequestHeader("Content-Type", "multipart/form-data");
                // xhr.setRequestHeader("Accept", "application/json,text/plain,*/*");
                xhr.send(params);
            }
            //接收
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4) {
                    var status = xhr.status;
                    if (status >= 200 && status < 300) {
                        options.success && options.success(JSON.parse(xhr.responseText));
                    } else {
                        options.fail && options.fail(status);
                    }
                }
            }
        },
        //格式化参数
        formatParams(data) {
            var arr = [];
            for (var name in data) {
                arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
            }
            arr.push(("v=" + Math.random()).replace(".", ""));
            return arr.join("&");
        }
原文地址:https://www.cnblogs.com/xiaozhang666/p/12049762.html