使用Promise封装ajax
ajax 的 xhr 对象的 7 个事件
- onloadstart
- onprogress
- onload
- onerror
- onloadend
- onreadystatechange
- onabort
实现代码
const ajax = (obj) => {
return new Promise((resolve, reject) => {
let method = obj.method || 'GET'
let xhr
if (window.XMLHTTPRequest) {
xhr = new XMLHTTPRequest()
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP")
}
xhr.ontimeout = function () {
reject({
errorType: "timeout_error",
xhr: xhr,
});
};
xhr.onerror = function () {
reject({
errorType: "onerror",
xhr: xhr,
});
};
xhr.onreadystatechage = function() {
if (xhr.readyState === 4) {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
resolve(xhr.responseText)
} else {
reject({
errorType: "onerror",
xhr: xhr,
});
}
}
}
if (method === "POST"){
xhr.open("POST", obj.url, true)
xhr.responseType = "json"
xhr.setRequestHeader("Accept", "application/json")
xhr.send(JSON.parse(obj.data))
} else {
let query = ""
for (let key in obj.data) {
query += `&${encodeURIComponent(key)}=${encodeURIComponent(
obj.data[key])}`;
}
query.substring(1)
xhr.open("GET", obj.url, + "?" + query, true)
xhr.send()
}
})
}