var baseUrl = 'http://localhost:4567'
var request = function (url, option, success, faild) {
var xhr = new XMLHttpRequest()
if (!url) throw new Error('必须传递url')
// 请求方法请求体
xhr.open(option.method || 'get', baseUrl + url)
// 判断请求头
if (option.headers) {
for (let headerName in option.headers) {
xhr.setRequestHeader(headerName, option.headers[headerName])
}
}
// 不同响应数据解析:text 文件等
if (option.responseType) {
xhr.responseType = option.responseType
}
// xhr.send()传递请求体
if (option.data) {
xhr.send(option.data)
} else {
xhr.send()
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
// 成功
if (xhr.status === 200) {
success(xhr.response)
} else {
console.log(xhr)
faild({
status: xhr.status,
statusText: xhr.statusText
})
}
}
}
}
request('/data', {}, function (data) {
console.log('成功', data);
}, function (e) {
console.log(e);
})
JS实现Ajax封装
于 2022-10-26 02:00:28 首次发布