原生js封裝的ajax請求

小編:啊南 13閱讀 2020.12.21

細節

發送POST數據,需要設置header頭:

將Content-Type頭部信息設置為application/x-www-form-urlencoded

ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

完整代碼參考:

(function (w) {
    var responseType = function (type, content) {
        switch (type) {
            case 'TEXT':
                return content;
            case 'JSON':
                return JSON.parse(content);
            default:
                return content;
        }
    };

    var param = function (a) {
        var s = [],
            rbracket = /\[\]$/,
            isArray = function (obj) {
                return Object.prototype.toString.call(obj) === '[object Array]';
            },
            add = function (k, v) {
                v = typeof v === 'function' ? v() : v === null ? '' : v === undefined ? '' : v;
                s[s.length] = encodeURIComponent(k) + '=' + encodeURIComponent(v);
            },
            buildParams = function (prefix, obj) {
                var i, len, key;

                if (prefix) {
                    if (isArray(obj)) {
                        for (i = 0, len = obj.length; i < len; i++) {
                            if (rbracket.test(prefix)) {
                                add(prefix, obj[i]);
                            } else {
                                buildParams(prefix + '[' + (typeof obj[i] === 'object' ? i : '') + ']', obj[i]);
                            }
                        }
                    } else if (obj && String(obj) === '[object Object]') {
                        for (key in obj) {
                            buildParams(prefix + '[' + key + ']', obj[key]);
                        }
                    } else {
                        add(prefix, obj);
                    }
                } else if (isArray(obj)) {
                    for (i = 0, len = obj.length; i < len; i++) {
                        add(obj[i].name, obj[i].value);
                    }
                } else {
                    for (key in obj) {
                        buildParams(key, obj[key]);
                    }
                }
                return s;
            };

        return buildParams('', a).join('&').replace(/%20/g, '+');
    };

    async function ajax(options) {
        options.method = options.method ? options.method.toUpperCase() : 'GET';
        options.dataType = options.dataType ? options.dataType.toUpperCase() : 'TEXT';
        options.data = options.data ? options.data : '';

        options.success = options.success ? options.success : function () {
        };
        options.fail = options.fail ? options.fail : function () {
        };
        if (!options.url) {
            throw new Error("there are no url.");
        }

        var ajax = new XMLHttpRequest();
        ajax.open(options.method, options.url, true);
        if (options.method === 'POST') {
            ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            ajax.send(typeof options.data === 'object' ? param(options.data) : options.data);
        } else {
            ajax.send();
        }
        ajax.onreadystatechange = function () {
            if (ajax.readyState === 4) {
                if (ajax.status === 200 || ajax.status === 301) {
                    options.success(responseType(options.dataType, ajax.responseText));
                } else {
                    throw new Error("the status of this request is't done.");
                }
            }

        };
    }

    w.ajax = ajax;

})(window);

其中param函數是參考:https://www.cnblogs.com/daysme/p/6651382.html

目的是發送post時,如果data參數是對象,那么將其轉換為字符串類型。

使用
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Title</title>
    <script src="ajax.js"></script>
    <script>
        window.onload = function () {
            let oBtn = document.getElementById('btn');
            oBtn.onclick = function () {
                ajax({
                    url: 'http://localhost:3000',
                    method: 'post',
                    data: 'aa=ff&dd=afjalk',
                    success: function (res) {
                        console.log(res);
                    },
                    dataType: 'json'
                })

            };

        };
    </script>
</head>
<body>
<button id="btn">Request</button>
</body>
</html>

核心就是:

ajax({
    url: 'http://localhost:3000',
    method: 'post',
    data: 'aa=ff&dd=afjalk', // data可以是這種字符串,也可以是對象{}
    success: function (res) {
        console.log(res);
    },
    dataType: 'json'
})
關聯標簽:
欧美日韩在线精品视频二区_日本高清在线精品一区_天天看片天天av免费观看