ES6封装原生ajax请求

    http (data) {
        return new Promise((resolve, reject) => {
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
                        resolve(xhr.responseText);
                    } else {
                        reject(xhr.status);
                    }
                } else {
                    // HTTP请求还在继续...
                }
            };
            xhr.open(data.methods, data.url, true);
            xhr.setRequestHeader('content-type', 'application/json');
            delete data.methods;
            delete data.url;
            xhr.send(JSON.stringify(data));
        });
    }

  

posted @ 2018-12-05 16:24  liliyou  阅读(763)  评论(0编辑  收藏  举报