定义
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) })
|