function ajax(options) {
const xhr = window.XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject;
const method = options.method.toLocaleLowerCase() || 'get';
const url = options.url + '?random=' + Math.random(); // 处理ie二次获取缓存的问题
const data = options.data;
const async = true;
const timeout = options.timeout || '20000' // 如果没有设置超时时间,则默认为20s
return new Promise((resolve, reject) => {
xhr.ontimeout = () => reject("请求超时");
xhr.onreadystatechange = () => {
if (xhr.readystate == 4) {
if (xhr.status >= 200 && xhr <= 300 || xhr == 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('&')
}
// get请求拼接参数
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)
}
})
}
封装ajax(promise封装)
最新推荐文章于 2024-06-08 13:56:48 发布