js实现ajax组件的开发

js实现ajax组件的开发

需求:

1.调用函数,执行ajax
2.输入的参数有四个,分别是地址,数据,发送方式,数据类型

分析:

  • 发送的数据类型有querystring数据,所以要把querystring重新改为ES6的封装

代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script type="module">
        import QueryString from "./js/QueryString.js";

        function ajax(url, data, method = "GET", type = "query") {
            return new Promise(function (resolve, reject) {
                if (type.toLowerCase() === "query") data = QueryString.stringify(data);
                else if (type.toLowerCase() === "json") data = JSON.stringify(data);
                var xhr = new XMLHttpRequest();
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        resolve(xhr.response);
                    } else if (xhr.readyState === 4 && xhr.status !== 200) {
                        reject(xhr.status);
                    }
                }
                xhr.open(method, url + "?" + (method.toLowerCase() === "get" ? data : ""));
                xhr.send((method.toLowerCase() === "get" ? "" : data));
            })
        }


        ajax("http://localhost:4006", { user: "xietian", age: 30 }, "POST", "JSON").then(function (res) {
            console.log(res);
        })
    </script>
</body>

</html>

querystring 重新封装为ES6

export default class QueryString {
    static stringify(obj, sep, eq, name) {
        sep = sep || '&';
        eq = eq || '=';
        if (obj === null) {
            obj = undefined;
        }

        if (typeof obj === 'object') {
            return Object.keys(obj).map(function (k) {
                var ks = encodeURIComponent(QueryString.stringifyPrimitive(k)) + eq;
                if (Array.isArray(obj[k])) {
                    return obj[k].map(function (v) {
                        return ks + encodeURIComponent(QueryString.stringifyPrimitive(v));
                    }).join(sep);
                } else {
                    return ks + encodeURIComponent(QueryString.stringifyPrimitive(obj[k]));
                }
            }).join(sep);

        }

        if (!name) return '';
        return encodeURIComponent(QueryString.stringifyPrimitive(name)) + eq +
            encodeURIComponent(QueryString.stringifyPrimitive(obj));
    }

    static stringifyPrimitive(v) {
        switch (typeof v) {
            case 'string':
                return v;

            case 'boolean':
                return v ? 'true' : 'false';

            case 'number':
                return isFinite(v) ? v : '';

            default:
                return '';
        }
    }
    static parse(qs, sep, eq, options) {
        sep = sep || '&';
        eq = eq || '=';
        var obj = {};

        if (typeof qs !== 'string' || qs.length === 0) {
            return obj;
        }

        var regexp = /+/g;
        qs = qs.split(sep);

        var maxKeys = 1000;
        if (options && typeof options.maxKeys === 'number') {
            maxKeys = options.maxKeys;
        }

        var len = qs.length;
        // maxKeys <= 0 means that we should not limit keys count
        if (maxKeys > 0 && len > maxKeys) {
            len = maxKeys;
        }

        for (var i = 0; i < len; ++i) {
            var x = qs[i].replace(regexp, '%20'),
                idx = x.indexOf(eq),
                kstr, vstr, k, v;

            if (idx >= 0) {
                kstr = x.substr(0, idx);
                vstr = x.substr(idx + 1);
            } else {
                kstr = x;
                vstr = '';
            }

            k = decodeURIComponent(kstr);
            v = decodeURIComponent(vstr);

            if (!QueryString.hasOwnProperty(obj, k)) {
                obj[k] = v;
            } else if (Array.isArray(obj[k])) {
                obj[k].push(v);
            } else {
                obj[k] = [obj[k], v];
            }
        }

        return obj;
    }
    static hasOwnProperty(obj, prop) {
        return Object.prototype.hasOwnProperty.call(obj, prop);
    }
}
原文地址:https://www.cnblogs.com/94-Lucky/p/13455418.html