原生js的ajax封装

let $ = {

    get: function ({ url, data = "", async = true, dataType = "text", success }) {
        let xhr = new XMLHttpRequest();

        if (typeof (data) == Object) {
            let str = "";
            for (const key in data) {
                str += key + "=" + data[key] + "&";
            }
            data = str.substring(0, str.length - 1);
        }
        xhr.open("get", data ? url + "?" + data : url, async);
        xhr.send();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                let result = xhr.responseText;
                if (dataType == "json") {
                    result = JSON.parse(result);
                    success(result);
                } else {
                    success(result);
                }

            }
        }
    },

    post: function ({ url, data = "", async = true, dataType = "text", success } = {}) {
        if (typeof (data) == Object) {
            let str = "";
            for (const key in data) {
                str += key + "=" + data[key] + "&";
            }
            data = str.substring(0, str.length - 1);
        }
        let xhr = new XMLHttpRequest();
        xhr.open("post", url, async);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send(data);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                let result = xhr.responseText;
                if (dataType == "json") {
                    result = JSON.parse(result);
                    success(result);
                } else {
                    success(result);
                }
            }
        }
    },
    ajax: function ({ type, url, data = "", async = true, dataType = "text", success }) {
        if (typeof (data) == "object") {
            let str = "";
            for (const key in data) {
                console.log(key);
                console.log(data, key);
                str += key + "=" + data[key] + "&";
            }
            data = str.substring(0, str.length - 1);
        }
        let xhr = new XMLHttpRequest();
        if (type == "get") {
            xhr.open("get", data ? url + "?" + data : url, async);
            xhr.send();
        } else if (type == "post") {
            xhr.open("post", url, async);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.send(data);
        }
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                let result = xhr.responseText;
                if (dataType == "json") {
                    result = JSON.parse(result);
                    success(result);
                } else {
                    success(result);
                }
            }
        }
    }
}



版权声明:本文为weixin_44649210原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。