封装原生AJAX

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX</title>
</head>
<body>
    <!-- 异步的javascript和XML -->
    <script>
        ;((function() {
            const root = typeof self == 'object' && self.self === self && self ||
                typeof global == 'object' && global.global === global && global ||
                Function('return this')() ||
                {};
            root.$$ = ((function(root) {
                let format = function (obj) {
                    let r = '';
                    for (let key in obj) {
                        r = r + key + '=' + obj[key] + '&';
                    }
                    return r.substr(0, r.length - 1);
                };
                let request = function (obj) {
                    let xhr = null;
                    if (root.XMLHttpRequest) {
                        xhr = new XMLHttpRequest();
                    } else if (root.ActiveXObject) {
                        xhr = new ActiveXObject('Microsoft.XMLHTTP');
                    } else {
                        throw new Error('请在支持ajax的环境下运行此脚本');
                    }
                    if (obj.url == void 0) {
                        throw new Error('请指定要请求的地址');
                    }
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState == 4) {
                            let res = JSON.parse(xhr.responseText);
                            if (xhr.status == 200) {
                                obj.success(res);
                            }
                            if (xhr.status == 404) {
                                obj.fail(res);
                            }
                            obj.complete(res);
                        }
                    };
                    xhr.open(obj.type, obj.url, true);
                    obj.type == 'POST' && xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                    xhr.send(obj.type == 'GET' ? null : format(obj.data));
                };
                return {
                    get: function (url, success = res => void 0, fail = res => void 0, complete = res => void 0) {
                        request({ type: 'GET', url, success, fail, complete });
                    }, 
                    post: function (url, data = {}, success = res => void 0, fail = res => void 0, complete = res => void 0) {
                        request({ type: 'POST', url, data, success, fail, complete });
                    }
                };
            })(root));
        })());

        /**
         * GET: $$.get(请求地址,成功回调,失败回调,完成回调);
         * POST: $$.post(请求地址,请求数据,成功回调,失败回调,完成回调);
         */
    </script>
</body>
</html>

 

posted @ 2021-01-21 12:01  吕洋  阅读(94)  评论(0)    收藏  举报