纵有疾风起
人生不言弃

用Promise封装一下原生ajax

function ajaxMise(url, method, data, async, timeout) {    var xhr = new XMLHttpRequest()    return new Promise(function (resolve, reject) {        xhr.open(method, url, async);        xhr.timeout = options.timeout;        xhr.onloadend = function () {            if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304)                resolve(xhr);            else                reject({                    errorType: 'status_error',                    xhr: xhr                })        }        xhr.send(data);        //错误处理        xhr.onabort = function () {            reject(new Error({                errorType: 'abort_error',                xhr: xhr            }));        }        xhr.ontimeout = function () {            reject({                errorType: 'timeout_error',                xhr: xhr            });        }        xhr.onerror = function () {            reject({                errorType: 'onerror',                xhr: xhr            })        }    })}

文章转载于:https://www.jianshu.com/p/35107f166a38

原著是一个有趣的人,若有侵权,请通知删除

未经允许不得转载:起风网 » 用Promise封装一下原生ajax
分享到: 生成海报

评论 抢沙发

评论前必须登录!

立即登录