// 把对象转为查询字符串
const getQueryString = (data) => {
let paramsArr = []
if (data instanceof Object) {
Object.keys(data).forEach((key) => {
let val = data[key]
paramsArr.push(encodeURIComponent(key) + '=' + encodeURIComponent(val))
})
}
return paramsArr.join('&')
}
const asyncThrowError = function (error) {
if (!(error instanceof Error)) {
error = new Error(error)
}
;(async (error) => {
throw error
})(error)
}
/**
* js封装ajax请求
* @param settings
*/
export default (settings = {}) => {
const headers = settings.headers || {}
// 初始化请求参数
let requestConfig = {
url: '', // string
method: 'POST', // string 'GET' 'POST' 'DELETE'
async: true, // boolean true:异步请求 false:同步请求 required
data: null, // any 请求参数,data需要和请求头Content-Type对应
timeout: false, // string 超时时间: false表示不设置超时
...settings,
headers: { 'Content-Type': 'application/json;charset=UTF-8', ...headers } // 请求头
}
// 参数验证
if (
!requestConfig.url ||
!requestConfig.method ||
requestConfig.async === undefined
) {
console.log('参数有误')
return
}
// 创建XMLHttpRequest请求对象
let xhr = new XMLHttpRequest()
xhr.withCredentials = true
// 请求成功回调函数
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
const status = xhr.status
if ((status >= 200 && status < 300) || status === 304) {
if (requestConfig.success && typeof requestConfig.success === 'function') {
let res = {};
try {
res = xhr.responseText ? JSON.parse(xhr.responseText) : {};
} catch (err) {
res.msg = 'responseText解析错误'
asyncThrowError(err)
}
requestConfig.success(res)
}
}
}
}
// 初始化请求
xhr.open(requestConfig.method, requestConfig.url, requestConfig.async)
// 设置请求头
for (const key of Object.keys(requestConfig.headers)) {
xhr.setRequestHeader(key, requestConfig.headers[key])
}
// 发送请求.如果是简单请求,请求参数应为null.否则,请求参数类型需要和请求头Content-Type对应
xhr.send(getQueryString(requestConfig.data))
}
简单封装XMLHttpRequest
于 2022-11-15 22:29:53 首次发布