【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);
    }
}

 

上一篇:Python3实现自动抽奖


下一篇:Python之Requests模块使用详解(六)