阮一峰大佬的《ES6标准入门》中所写,记录一下
var getJSON = function(url){
var promise = new Promise((resolve, reject)=>{
let client = new XMLHttpRequest();
clint.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;
}
//调用ajax
getJSON('/posts.json').then((json)=>{
console.log(`Contents: ${json}`)
}), (error)=>{
console.error(`error: ${error}`)
}