<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
// 基于Promise实现Ajax的封装
function ajax(optins) {
// 1. 解构获取传入的参数
let { method, url, async, data, timeout } = optins
// 2. 对象实例化
const xhr = new XMLHttpRequest()
// 3. 设置超时信息
if (timeout && timeout > 0) {
xhr.timeout = timeout
}
// 4. 返回一个Promise对象
return new Promise((resolve, reject) => {
// 5. 请求参数处理
let params = []
let encodeData = ''
if (data instanceof Object) {
Object.keys(data).forEach((key) => {
params.push(
`${encodeURIComponent(
key
)}=${encodeURIComponent(data[key])}`
)
})
encodeData = params.join('&')
}
if (method === 'get') {
const index = url.indexOf('?')
if (index === -1) {
url += '?'
} else if (index !== url.length - 1) {
url += '&'
}
url += encodeData
}
// 6. 初始化连接
xhr.open(method, url, async)
// 7.发送请求
if (method === 'get') {
xhr.send()
} else {
xhr.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded'
)
xhr.send(encodeData)
}
// 8.接收请求
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (
(xhr.status >= 200 && xhr.status < 300) ||
xhr.status === 304
) {
resolve(xhr.response)
} else {
reject(xhr.response)
}
}
}
// 9.错误处理
xhr.ontimeout = () => reject('请求超时')
xhr.onerror = () => reject(err)
})
}
let params = {
method: 'get',
url: 'https://api.uomg.com/api/rand.qinghua',
async: true,
}
ajax(params).then((res) => {
console.log(res, 'res')
document.write(JSON.parse(res).content)
})
</script>
</body>
</html>
基于Promise实现Ajax请求封装
于 2022-08-16 23:52:11 首次发布