1.创建对象
const xhr =new XMLHttpRequest();
2.初始化对象 接口为示例
xhr.open("GET","https://api.apiopen.top/getlogin");
3.发送请求
xhr.send();
4.绑定事件,处理响应结果
xhr.onreadystatechange = function(){
//判断状态
if(xhr.readyState === 4){
//判断响应码
if(xhr.status >= 200 && xhr.status <= 300){
//成功,处理xhr.response
}else{
//失败,抛出错误
console.error(xhr.status);
}
}
}
使用Promise封装
const p =new Promise((resolve,reject)=>{
const xhr = new XMLHttpRequest();
xhr.open("GET","https://api.apiopen.top/gelogin");
xhr.open();
xhr.onreadyStatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status <= 300){
//成功,处理xhr.response
resolve(xhr.response);
}else{
//失败,抛出错误
console.error(xhr.status);
reject(xhr.status);
}
}
}
});
//指定回调
p.then(function(value){
console.log(value);
}),function(reason){
console.error(reason);
}