话不多说,代码:
function ajaxPromise(url, method = 'GET', data, dataType='JSON', async = 'true', timeout) {
let xhr = new XMLHttpRequest();
return new Promise((resolve, reject) => {
xhr.open(method, url, async);
xhr.responseType = dataType;
xhr.timeout = timeout;
xhr.onreadystatechange = () => {
// 简单的请求成功判断
if (xhr.readyState === 4 && xhr.status === 200) {
let result = xhr.responseText;
resolve(result);
} else {
reject(new Error());
}
}
xhr.send(data);
// 错误处理
xhr.onabort = function() {
reject(new Error({
msg: 'abort error',
xhr: xhr
}));
}
xhr.ontimeout = function() {
reject({
msg: 'ajax timeout',
xhr: xhr
});
}
xhr.onerror = function() {
reject({
msg: 'onerror',
xhr: xhr
})
}
})
}
Comments | NOTHING