xhr 具有以下常用属性:
responseText: 请求返回的数据内容
responseXML: 如果响应内容是"text/xml"“application/xml”,这个属性将保存响应数据的 XML DOM文档
status: 响应的HTTP状态,如 200 304 404 等
statusText: HTTP状态说明
readyState: 请求/响应过程的当前活动阶段
timeout: 设置请求超时时间
- xhr.readyState==0 尚未调用 open 方法
- xhr.readyState==1 已调用 open 但还未发送请求(未调用 send)
- xhr.readyState==2 已发送请求(已调用 send)
- xhr.readyState==3 已接收到请求返回的数据
- xhr.readyState==4 请求已完成
function ajax(options) {
let url = options.url
const method = options.method.toLocaleLowerCase() || 'get'
const async = options.async != false // default is true
const data = options.data
const xhr = new XMLHttpRequest()
if (options.timeout && options.timeout > 0) {
xhr.timeout = options.timeout
}
return new Promise((resolve, reject) => {
xhr.ontimeout = () => reject && reject('请求超时')
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
resolve && resolve(xhr.responseText)
} else {
reject && reject()
}
}
}
xhr.onerror = err => reject && reject(err)
let paramArr = []
let encodeData
if (data instanceof Object) {
for (let key in data) {
// 参数拼接需要通过 encodeURIComponent 进行编码
paramArr.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
}
encodeData = paramArr.join('&')
}
if (method === 'get') {
// 检测 url 中是否已存在 ? 及其位置
const index = url.indexOf('?')
if (index === -1) url += '?'
else if (index !== url.length - 1) url += '&'
// 拼接 url
url += encodeData
}
xhr.open(method, url, async)
if (method === 'get') xhr.send(null)
else {
// post 方式需要设置请求头
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8')
xhr.send(encodeData)
}
})
}
总结
- 创建一个xhr
- .open设置参数
- .onreadystatechange设置返回状态的处理
- .send发送请求