Voyz's Studio.

用ES6手写一个ajax

字数统计: 96阅读时长: 1 min
2018/08/11 Share

定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const myAjax = url => {
return new Promise((resolve,reject) => {
let client = new XMLHttpRequest();
client.open("GET",url);
client.onreadystatechange = handler;
client.responseType = "json";
client.setRequsetHeader("Accept","application/json");
client.send();
handler = function() {
if(this.readyState != 4) return;
if(this.status === 200){
resolve(this.response)
}else {
reject(new Error(this.statusText))
}
}
})
}

使用

1
2
3
4
5
myAjax('http://blog.voyz.vip').then(res => {
console.log(res)
}).catch(error => {
console.log(error)
})
CATALOG
  1. 1. 定义
  2. 2. 使用