xhr的请求状态readystate的五个参数
0 请求未初始化 send()未调用
1 与服务器建立连接 send()未调用
2 请求已发送,正在处理中
3 请求未完成 返回部分数据
4 请求完成 返回全部数据
<script>
// GET方法
function myAJAX(url) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) {
return
}
if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
resolve(xhr.responseText)
} else {
reject(new Error('请求错误'))
}
}
})
}
// POST方法 需要设置请求头 并且数据在send(data)中发送
function myAJAX(url, data) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest()
xhr.open('POST', url, true)
// 需要设置请求头
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
xhr.send(data)
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) {
return
}
if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
resolve(xhr.responseText)
} else {
reject(new Error('请求错误'))
}
}
})
}
// xhr.readyState的五个状态
// 0 请求未初始化 未调用send()
// 1 已与服务器建立连接 未调用send()
// 2 请求已发送,正在处理中
// 3 请求未完成,已有部分数据返回
// 4 响应完成 全部数据返回
</script>