【ES6】es6封装好的ajax请求 (类实现)

以下是封装好的es6 ajax请求

class Ajax {
    constructor(xhr) {
        xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
        this.xhr = xhr;
    }

    send(options) {
        let xhr = this.xhr;

        let opt = {
            type: options.type || 'GET',
            url: options.url || '',
            async: options.async || 'true',
            dataType: options.dataType || 'json',
            questring: options.questring || ''
        };

        return new Promise((resolve, reject) => {
            xhr.open(opt.type,opt.url,opt.async);

            xhr.onreadystatechange = () => {
                if(xhr.readyState === 4) {
                    if(xhr.status === 200){
                        if(opt.dataType === 'json'){
                            const data = JSON.parse(xhr.responseText);
                            resolve(data);
                            console.log(data);
                        }
                    }else {
                        reject(new Error(xhr.status || 'Server is fail.'));
                    }
                }
            };
            xhr.onerror = () => {
                reject(new Error(xhr.status || 'Server is fail.'));
            };
            xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xhr.send(opt.questring);
        })
    }
}

用法

let ajax = new Ajax();
ajax.send({
    type : 'POST',
    url:'https://www.baidu.com/api/newsList.php'
});

经测试可用。
如有缺漏,请指出。谢谢。
挚谢阅读。

你可能感兴趣的:(技术之路,原创,js效果)