原生ajax是XMLHttpRequest,监听readyStateChange事件,关注readyState和status。
const ajax = url
=> {
return new Promise((resolve
, reject
) => {
const xhr
= new XMLHttpRequest()
xhr
.open('GET', url
, true)
xhr
.setRequestHeader('Accept', 'application/json')
xhr
.onreadystatechange = () => {
if (xhr
.readyState
!== 4) {
return
}
if (xhr
.status
=== 200 || xhr
.status
=== 304) {
resolve(xhr
.responseText
)
} else {
reject(new Error(xhr
.responseText
))
}
}
xhr
.send()
})
}
转载请注明原文地址:https://blackberry.8miu.com/read-31793.html