模拟写一个AJAX

2019-01-08  本文已影响0人  yoolika

onreadystatechange 事件

注册 onreadystatechange 事件后,每当 readyState 属性改变时,就会调用 onreadystatechange 函数。

readyState:(存有 XMLHttpRequest 的状态。从 0 到 4 发生变化)

<script>
    var util = {};

    //获取 ajax 请求之后的json
    util.json = function (options) {

        var opt = {
            url: options.url || '',
            type: options.type || 'get',
            data: options.data || {},
            success: function (res) {
                options.success ? options.success(res) : console.log("success");
            },
            error: function (res) {
                options.error ? options.error(res) : console.log("error");
            },

        };
        if (opt.url) {
            //IE兼容性处理:浏览器特征检查。检查该浏览器是否存在XMLHttpRequest这个api,没有的话,就用IE的api
            var xhr = XMLHttpRequest ? new XMLHttpRequest() : new window.ActiveXObject('Microsoft.XMLHTTP');

            var data = opt.data,
                url = opt.url,
                type = opt.type.toUpperCase();
            dataArr = [];
        }

        for (var key in data) {
            dataArr.push(key + '=' + data[key]);
        }

        if (type === 'GET') {
            url = url + '?' + dataArr.join('&');
            xhr.open(type, url.replace(/\?$/g, ''), true);
            xhr.send();
        }

        if (type === 'POST') {
            xhr.open(type, url, true);
            // 如果想要使用post提交数据,必须添加此行
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhr.send(dataArr.join('&'));
        }
        xhr.onreadystatechange = () => {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {  //304表示:用缓存即可。206表示获取媒体资源的前面一部分
                    var res;
                    if (opt.success && opt.success instanceof Function) {
                        res = xhr.responseText;
                        if (typeof res === 'string') {
                            res = JSON.parse(res);  //将字符串转成json
                            opt.success.call(xhr, res);
                        }
                    }
                } else {

                    if (opt.error && opt.error instanceof Function) {
                        opt.error.call(xhr, 'error');
                    }
                }
            }
        }
    }

    util.json({
        url: 'http://localhost:3000/v1/getgame/EPhej0vhbUO9xd78BlbJPg',
        type: 'get',
        data: {},
        success: function (res) {
            console.log(res)
        },
        error: function (error) {
            console.log(error)
        }
    });
</script>

ES6写法:

export default (type='GET', url='', data={}, async=true) => {
    return new Promise((resolve, reject) => { //定义一个promise
        type = type.toUpperCase();

        let requestObj;
        if (window.XMLHttpRequest) {
            requestObj = new XMLHttpRequest();
        } else {
            requestObj = new ActiveXObject;
        }

        if (type == 'GET') {
            let dataStr = ''; //数据拼接字符串
            Object.keys(data).forEach(key => {
                dataStr += key + '=' + data[key] + '&';
            })
            dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
            url = url + '?' + dataStr;
            requestObj.open(type, url, async);
            requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            requestObj.send();
        }else if (type == 'POST') {
            requestObj.open(type, url, async);
            requestObj.setRequestHeader("Content-type", "application/json");
            requestObj.send(JSON.stringify(data));
        }else {
            reject('error type');
        }

        requestObj.onreadystatechange = () => {
            if (requestObj.readyState == 4) {
                if (requestObj.status == 200) {
                    let obj = requestObj.response
                    if (typeof obj !== 'object') {
                        obj = JSON.parse(obj);
                    }
                    resolve(obj);
                }else {
                    reject(requestObj);
                }
            }
        }
    })
}
上一篇 下一篇

猜你喜欢

热点阅读