一般的ajax申请:
//创立一个对象
let xhr = new XMLHttpRequest();
//申明申请的形式和门路
xhr.open('get',url);
//发送申请
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
console.log(JSON.parse(xhr.responseText));
}
}
应用promise的ajax申请:
let getJSON = fucntion(url){
let promise = new Promise(function(resolve,reject){
let client = new XMLHttpRequest();
client.open('get',url);
client.onreadystatechange = handler;
client.responseType = 'json';
client.setRequestHeader('Accept','application/json');
client.send();
function handler(){
if(this.readyState !== 4)return;
if(this.status === 200){
resolve(this.response);
}else{
reject(new Error(this.statusText));
}
}
});
return promise;
}
getJSON('url').then(function(){
console.log('内容是:' + json);
},function(){
console.log('出错了',err);
})
发表回复