Promise封装ajax

763 阅读1分钟

XMLHttpRequest

设置请求头类型

type code
表单字符类型 application/x-www-form-urlencoded
表单类型 multiline/form-data
json 类型 application/json
xhr = new XMLHttpRequest();
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

Promise

  • Promise对象代表一个异步操作,有三种状态:
    • pending 进行中
    • fulfilled 已成功
    • rejected 已失败

对象的状态不受外界影响,一旦状态改变,就不会再变

  • Promise对象的状态改变,只有两种可能:
    • pending => fulfilled
    • pending => rejected

JavaScript封装XMLHttpRequest

function pmiseAjax(type, url, data) {

    return new Promise(function(resolve, reject) {

        var xhr = null
        if (window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        } else {
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }

        xhr.open(type, url, true);

        xhr.onreadystatechange = function(){
            if (xhr.readyState == 4 && xhr.status == 200) {
                resolve(JSON.parse(xhr.responseText));
            } else {
                reject(xhr)
            }
        }

        if (type == 'GET') {
            xhr.send()
        } else {
            xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xhr.send(formatParams(data));
        }

    })

    function formatParams(data) {
        var arr = [];
        for(var name in data){
            arr.push(name + '=' + data[name]);
        }
        return arr.join("&");
    }
}

jQuery封装$.ajax

function pmiseAjax(options) {
    return new Promise(function(resolve, reject) {
        var $params = $.extend({ type: "GET", url: "", data: {}, global: false, async: true }, options);
        var $callback = callback || "";

    // console.log($params);
    $.ajax({
        type: $params.type,
        url: $params.url,
        async: $params.async,
        data: $params.data,
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        // 触发全局AJAX事件  true:默认值,打开全局事件;false:关闭
        global: $params.global, 
        cache: false,
        success: function(data) {
            resolve(data);
        },
        error: function(err) {
            reject(error);
        },
        beforeSend: function(xhr) {
            if ($.isFunction($params.beforeSend)) {
                $params.beforeSend(xhr);
            }
        },
        complete: function(xhr) {
            // return;
            if ($.isFunction($params.complete)) {
                $params.complete(xhr);
            }
        }
    });
    })
}