使用Promise封装一个ajax请求
// Promise封装原生ajax请求
function ajaxFun(data){
return new Promise((resolve,reject)=>{
const xhr = new XMLHttpRequest()
xhr.open(data.method,data.url)
xhr.send()
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status >= 200 && xhr.status < 300){
resolve(xhr.response)
} else{
reject(xhr.status)
}
}
})
}
//封装函数调用
ajaxFun({
method:'post'
url:'xxxxxxx'
}).then(res=>{
console.log(res)
}).catch(err=>{
console.log(err)
})