//promise封装Ajax
// 创建ajax的四个步骤
// 1.创建ajax对象
var xhr = new XMLHttpRequest();
// 兼容IE低版本浏览器
xhr = new ActiveXObject('Microsoft.XMLHTTP');
// 2,监听ajax状态变化
xhr.onreadystatechange = function(){}
// 3,建立服务器连接
xhr.open('请求方式,请求路径,是否异步');
// 4,发起请求
xhr.send(null);
let api={
// get请求方法
get(){
return new Promise((reslove,reject)=>{
创建ajax
let xhr = null;
if(window.XMLHttpRequest){
// 如果有的话,创建一个ajax对象
xhr = new XMLHttpRequest();
}else{
// 如果没有的话
// 为IE低版本兼容
xhr= new ActiveXObject('Microsoft.XMLHTTP')
}
// 监听ajax对象状态的变化
xhr.onreadystatechange=function(){
// 如果ajax对象的状态为4且状态码为200
if(this.readyState == 4&&this.status==200){
// 成功凝固结果
reslove(this.responseText);
}
}
// 开始建立服务器连接
xhr.open('GET','http://api/',true);
// 发起请求
xhr.send(null);
}
)
}
}
api.get().then(res=>{
console.log(res);
}).catch(rej=>{
console.log(rej)
})
浏览器API,promise封装Ajax
最新推荐文章于 2022-04-28 18:19:54 发布