ajax封装

function ajax(options) {
    options = options || {};  //调用函数时如果options没有指定,就给它赋值{},一个空的Object
    options.type = (options.type || "GET").toUpperCase();/// 请求格式GET、POST,默认为GET
    options.dataType = options.dataType || "json";    //响应数据格式,默认json
    options.headers = options.headers || [];
    var params = formatParams(options.data);//options.data请求的数据

    var xhr;

    //考虑兼容性
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else if (window.ActiveObject) {//兼容IE6以下版本
        xhr = new ActiveXobject('Microsoft.XMLHTTP');
    }

    //启动并发送一个请求
    if (options.type == "GET") {
        xhr.open("GET", options.url + "?" + params, true);
        for (let i = 0; i < options.headers.length; i++) {
            xhr.setRequestHeader(options.headers[i][0], options.headers[i][1]);
        }
        xhr.send(null);
    } else if (options.type == "POST") {
        xhr.open("post", options.url, true);

        //设置表单提交时的内容类型
        //Content-type数据请求的格式
        xhr.setRequestHeader("Content-type", options.contentType || "application/json");
        for (let i = 0; i < options.headers.length; i++) {
            xhr.setRequestHeader(options.headers[i][0], options.headers[i][1]);
        }
        xhr.send(JSON.stringify(options.data));
    }

    //    设置有效时间
    setTimeout(function () {
        if (xhr.readySate != 4) {
            xhr.abort();
        }
    }, options.timeout || 10000);
    //    接收
    //     options.success成功之后的回调函数  options.error失败后的回调函数
    //xhr.responseText,xhr.responseXML  获得字符串形式的响应数据或者XML形式的响应数据
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            var status = xhr.status;
            if (status >= 200 && status < 300 || status == 304) {
                options.success && options.success(JSON.parse(xhr.responseText));
            } else {
                options.error && options.error(status);
            }
        }
    }
}

//格式化请求参数
function 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("&");

}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容