创建Ajax并用Promise封装
1. 创建Ajax
let xhr = new XMLHttpRequest();
xhr.open('get','xxxx',true);
xhr.onreadystatechange = () =>{
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status <300 || xhr.status === 304){
resolve(JSON.parse(xhr.responseText))
}else{
reject(new Error(xhr.statusText))
}
}
xhr.send();
}
2. Promise封装Ajax
function ajaxPromise(){
let promise= new Promise((resolve,reject)=>{
let xhr = new XMLHttpRequest();
xhr.open('get','xxx');
xhr.onreadystatechange = ()=>{
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status <300|| xhr.status === 304){
resolve(JSON.parse(xhr.responseText))
}else{
reject(new Error(xhr.statusText))
}
}
}
xhr.send();
})
return promise
}
let btn = document.querySelector("button")
btn.onclick = ()=>{
ajaxPromise().then((res)=>{
console.log(res)
})
.catch((err)=>{
console.log(err)
})
}