js原生ajax请求封装
<script>
    function ajaxData(obj) {
        let method = obj.method || 'GET'; //请求方式,默认get
        let data = obj.data || {};
        let header = obj.headers || [];
        return new Promise(function(resolve, Rejected) {
            const httpRequest = new XMLHttpRequest(); //第一步:建立所需的对象
            if (!obj.url) {
                Rejected(new Error('请求URL错误'))
                return
            };
            switch (method) {
                case "GET":
                    let _str = "";
                    for (let o in data) {
                        _str += o + "=" + data[o] + "&";
                    };
                    obj.url = obj.url + '?' + _str.slice(0, _str.length - 1); //拼接url参数
                    httpRequest.open(method, obj.url,true); //第二步:打开连接  将请求参数写在url中  ps:"./Ptest.php?name=test&nameone=testone"
                    if (header.length >= 2) { //请求头设置
                        httpRequest.setRequestHeader(header[0], header[1]);
                    };
                    httpRequest.send();
                    break;
                case "POST":
                    httpRequest.open('post', obj.url, true);
                    if (header.length >= 2) {
                        httpRequest.setRequestHeader(header[0], header[1]);
                    };
                    if (JSON.stringify(data) === "{}") {
                        httpRequest.send();
                    } else {
                        httpRequest.send(JSON.stringify(data));
                    }
                    break;
                default: //其他请求方式
                    httpRequest.open(method, obj.url, true);
                    if (header.length >= 2) {
                        httpRequest.setRequestHeader(header[0], header[1]);
                    };
                    if (JSON.stringify(data) === "{}") {
                        httpRequest.send();
                    } else {
                        httpRequest.send(JSON.stringify(data));
                    }
                    break;
            }
            /**
             * 获取数据后的处理程序
             */
            httpRequest.onreadystatechange = function() {
                if (httpRequest.readyState == 4 && httpRequest.status == 200) {
                    var json = httpRequest.responseText; //获取到json数据
                    resolve(json)
                }
            }
        });
    };
    let url = 'http://localhost:3000/'
    // 调用请求格式
    ajaxData({
        url: url + 'list',
        method: "GET",
        data: {
            a: 11,
            b: 'ooop'
        },
    }).then((res) => {
        console.log(res)
    });

    ajaxData({
        url: url + 'regisnt',
        method: 'POST',
        data: {
            name: '马丁的车夫',
            age: 18
        },
        headers: ['Content-Type', 'application/x-www-form-urlencoded']
    }).then((res) => {
        console.log(res, '===99')
    });
</script>

 

我是马丁欢迎转发和收藏。

 
posted on 2020-12-04 00:00  马丁的车夫  阅读(286)  评论(9编辑  收藏  举报