普通的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);
})
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。