ajax实现原理:通过XMLHttpResquest对象来向服务器发起异步请求,从服务器上获得数据,然后用javascript来操作DOM更新页面,这其中最关键的步骤就是从服务器上获得请求的数据。
var getJSON=function(url){
return new Promise((resolve,reject)=>{
let xhr=new XMLHttpRequest();
//第三个参数表示是异步还是同步,true表示异步,false表示同步
xhr.open("GET",url,true);
xhr.onreadystatechange=function(){
if(xhr.readyState!==4){
return;
}
if(xhr.status===200){
resolve(xhr.responseText);
}else{
reject(new Error(xhr.statusText));
}
};
xhr.responseType="json";
xhr.setResponseHeader("Accept","application/json");
xhr.send(null);
});
}
getJSON("/posts.json").then(function(json){
console.log(json);
},function(error){
console.log(error);
})