网络请求
XMLHttpRequest
基本使用
使用XMLHttpRequest 发送请求需要执行以下几步
- 使用 new XMLHttpRequest创建xhr对象
- xhr.open 初始化请求参数
- xhr.send 发送网络请求
- xhr.onload 监听请求结果
- xhr.onerror 请求中断等错误发生时的处理
响应类型
通过设置 xhr.responseType 对响应结果进行声明,来对结果自动进行处理。
下面是可以使用的响应类型
类型 | 说明 |
---|---|
text | 响应结果为文本 |
json | 响应内容为JSON,系统会自动将结果转为JSON对象 |
blob | 二进制数据响应 |
document | XML DOCUMENT 内容 |
响应结果
xhr.onload 用于处理响应完毕后的处理
使用以下属性来处理结果
- xhr.status 为HTTP状态码 如 404/422/403等,当为200时为正确响应
- xhr.statusText HTTP状态码内容,200时为ok,404 为Not Found
- xhr.response 服务器端响应的内容
readyState
返回值 | 说明 |
---|---|
0 | 未初始化。表示对象已经建立,但是尚未初始化,尚未调用 open() 方法 |
1 | 初始化。表示对象已经建立,尚未调用 send() 方法 |
2 | 发送数据。表示 send() 方法已经调用,但是当前的状态及 HTTP 头未知 |
3 | 数据传送中。已经接收部分数据,因为响应及 HTTP 头不安全,这时通过 responseBody 和 responseText 获取部分数据会出现错误 |
4 | 完成。数据接收完毕,此时可以通过 responseBody 和 responseText 获取完整的响应数据 |
xhr.abort()
终止请求
xhr.onreadystatechange = function () {}; //清理事件响应函数
xhr.abort() //中止请求
onreadystatechange
存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。
基本使用
const xhr = new XMLHttpRequest()
xhr.timeout = 5000
xhr.open('GET', 'http://api.kunyun.site/mock/20/test')
xhr.responseType = 'json'
xhr.onreadystatechange = function() {
console.log('state')
const state = xhr.readyState
console.log(state)
if (state === 3) {
xhr.onreadystatechange = null
xhr.abort()
}
console.log('state')
}
xhr.onerror = function(err) {
console.error(err)
}
xhr.onload = function() {
if (xhr.status == 200) {
console.log(xhr.response)
} else {
console.log(`${xhr.status}:${xhr.statusText}`)
}
}
xhr.send()
封装请求
class Ajax {
options = {
responseType: 'json',
timeout: 5 * 1000
}
constructor(method = 'GET', url, data = null, options) {
this.method = method
this.url = url
this.data = this.formatData(data)
}
formatData(data) {
if (typeof data != 'object' || data == null) data = {}
let form = new FormData()
for (const [name, value] of Object.entries(data)) {
form.append(name, value)
}
return form
}
static get(url, options) {
return new this('GET', url, null, options).xhr()
}
static post(url, data, options) {
return new this('POST', url, data, options).xhr()
}
xhr() {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open(this.method, this.url)
xhr.responseType = this.options.responseType
xhr.timeout = this.options.timeout
xhr.send(this.data)
xhr.onload = function () {
if (xhr.status !== 200) {
reject({
status: xhr.status,
error: xhr.statusText
})
} else {
resolve(xhr.response)
}
}
xhr.onerror = function(err) {
reject(err)
}
})
}
}