【js】【Demo】js-ajaxProtogenesis

js原生請求XMLHttpRequest封裝

//js原生請求XMLHttpRequest
const ajaxProtogenesis = {
    post: function (url, data, success, error, headers) {
        //默認application/json
        if (!headers) {
            headers = { "Content-type": "application/json" };
        }
        this.ajax('post', url, true, data, success, error, headers);
    },
    get: function (url, success, error, headers) {
        this.ajax('get', url, true, null, success, error, headers);
    },
    ajax: function (method, url, async, data, success, error, headers, updateProgress) {
        //請求對象
        var xhr = new XMLHttpRequest();

        //請求類型,請求地址 .open(method, url, async, user, password);
        if (!method) { method = "post" }
        if (async == undefined || async == null) { async = true }
        xhr.open(method, url, async);

        xhr.responseType = 'json';//返回數據解析類型

        //狀態事件
        xhr.onreadystatechange = function () {
            //readyState=4請求完成
            if (xhr.readyState == 4) {
                var res = xhr.response;

                if (xhr.status == 200) {
                    if (success) {
                        success(res);
                    }
                } else if (error) {
                    error(res);
                }
            }
        };

        //// 請求成功回調函數readyState等於4
        //xhr.onload = e => {
        //    console.log('request success');
        //    console.log(e.explicitOriginalTarget.responseText);
        //};
        //// 請求結束
        //xhr.onloadend = e => {
        //    console.log('request loadend');
        //    console.log(e.explicitOriginalTarget.responseText);
        //};
        //// 請求出錯
        //xhr.onerror = e => {
        //    console.log('request error');
        //    console.log(e.explicitOriginalTarget.responseText);
        //};
        //// 請求超時
        //xhr.ontimeout = e => {
        //    console.log('request timeout');
        //    console.log(e.explicitOriginalTarget.responseText);
        //};
        //xhr.timeout = 0; // 設置超時時間,0表示永不超時

        //傳輸進度獲取 //var updateProgress=function (event) {if (event.lengthComputable) { var completedPercent = event.loaded / event.total;  } }
        if (updateProgress) {
            //xhr.onprogress = updateProgress;當readyState等於3
            //xhr.upload.onprogress = updateProgress;
            xhr.upload.addEventListener("progress", updateProgress, false);
        }

        //請求頭//formData參數不能設置請求頭
        if (headers) {
            for (var i in headers) {
                xhr.setRequestHeader(i, headers[i]);
            }
        }

        //json對象參數轉json字符串
        if (headers && headers["Content-type"].toLowerCase() == "application/json") {
            if (typeof (data) == "object") {
                data = JSON.stringify(data);
            }
        }

        //參數,發出請求xhr.send(null || new FormData || 'a=1&b=2' || 'json字符串');
        xhr.send(data);

        //終止請求xhr.abort();
    },
    formData: function (url, data, success, error, updateProgress) {
        //data例{ planId: planId, file: document.getElementById("fileUpload").files[0] }
        //updateProgress傳輸進度回調
        let formData = new FormData();
        for (var i in data) {
            formData.append(i, data[i]);
        }

        //formData參數不能設置請求頭
        this.ajax("POST", url, true, formData, success, error, null, updateProgress);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章