一.基于回调函数
var $ = {
//基于回掉函数机制
get(url){
//异步交互
//1.new xhr实例
let xhr = new XMLHttpRequest();
//2.设置请求行
xhr.open('get',url)
//3.设置请求头
xhr.setRequestHeader("Content-Type", "application/json")
//4.发送请求
xhr.send()
//5.监听
xhr.onreadystatechange = function(){
if(this.readyState == 4 && this.status ==200){
success(this.response)
}else {
error(this)
}
}
}
}
使用
$.get({
url:'请求数据的接口地址',
success:function(res){
console.log(JSON.parse(res));
},
error:function(error){
console.log(error);
}
})
二.基于承诺对象
var axios = {
//基于承诺对象机制
get(url){
return new Promise(function(resolve,reject){
//1.new xhr实例
let xhr = new XMLHttpRequest();
//2.设置请求行
xhr.open('get',url)
//3.设置请求头
xhr.setRequestHeader("Content-Type", "application/json")
//4.发送请求
xhr.send()
//5.监听
xhr.onreadystatechange = function(){
if(this.readyState == 4){
if(this.status == 200){
resolve(this.response)
}else {
reject(this.response)
}
}
}
})
}
}
使用
axios.get('请求数据的接口地址')
.then((res)=>{
console.log(JSON.parse(res));
})
.catch((err)=>{
console.log(err);
})