// 新建一个Promise对象
const Pro = new Promise((resolve, reject) => {
// 1.创建对象
const xhr = new XMLHttpRequest();
// 2.初始化,设置请求方式和接口地址
xhr.open("GET", "接口地址");
// 3.发送请求
xhr.send();
// 4.绑定事件,处理响应结果
xhr.onreadystatechange = function () {
// 判断
if (xhr.readyState === 4) {
// 判断响应状态码 200~299
if (xhr.status >= 200 && xhr.status < 300) {
// 获取成功
resolve(xhr.response);
// console.log(xhr.response);
} else {
// 获取失败
reject(xhr.status);
// console.log(xhr.status);
}
}
}
});
// 处理状态
Pro.then((value) => {
console.log("成功:", value);
}, (reason) => {
console.log("失败:", reason);
})
使用Promise封装ajax请求
最新推荐文章于 2022-11-13 10:59:12 发布