一、get请求
//封装get请求
function get(url, success, error) {
// 创建核心对象
const xhr = new XMLHttpRequest()
// 初始化请求
xhr.open('GET', url, true)
// 发送请求
xhr.send(null)
// 处理响应
xhr.onreadystatechange = () => {
// 请求处理完毕,响应就绪
if (xhr.readyState === 4) {
// HTTP 状态码为 200 表示成功
if (xhr.status === 200) {
// 利用 JSON.parse() 方法将响应数据反序列化
const data = JSON.parse(xhr.responseText)
// 如果存在响应成功执行的回调函数,则调用并传递成功的数据
success && success(data)
} else {
// 如果存在失败执行的回调函数,则调用
error && error(new Error('请求失败,HTTP状态码为:' + xhr.status))
}
}
}
}
二、post请求(基于promise,不需要删除即可)
//封装post请求
function post(url, data) {
// 创建 Promise 对象,并返回
return new Promise((resolve, reject) => {
// 创建核心对象
const xhr = new XMLHttpRequest()
// 初始化请求
xhr.open('POST', url, true)
// 需要像表单一样 POST 提交文本数据
xhr.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded'
)
// 发送请求
xhr.send(data)
// 处理响应
xhr.onreadystatechange = () => {
// 请求处理完毕,响应就绪
if (xhr.readyState === 4) {
// HTTP 状态码为 200,表示成功
if (xhr.status === 200) {
// 反序列化响应结果
const data = JSON.parse(xhr.responseText)
// 标记 Promise 状态为 fulfilled,并传递成功的数据
resolve(data)
} else {
// 标记 Promise 状态为 rejected,传递Error对象
reject(new Error('请求失败,HTTP状态码为:' + xhr.status))
}
}
}
})
}