使用Promise来封装ajax请求
需要引入的js文件:此处命名为ajax.js
1 //实现自定义异常 2 class ParamError extends Error { 3 constructor(msg) { 4 super(msg); 5 this.name = 'ParamError'; 6 } 7 } 8 class HttpError extends Error { 9 constructor(msg) { 10 super(msg); 11 this.name = 'HttpError'; 12 } 13 } 14 15 function request(url) { 16 return new Promise((resolve, reject) => { //此处限制只能是https开头的协议 17 if (!/^https:/.test(url)) throw new ParamError('地址格式错误'); 18 let xhr = new XMLHttpRequest(); 19 xhr.open('get', url); 20 xhr.send(); 21 xhr.onload = function() { //onload中是异步请求数据,不可以直接来throw,或者直接在里面throw并解决异常 22 if (this.status == 200) resolve(JSON.parse(this.responseText)); 23 else if (this.status == 404) reject(new HttpError('请求的数据不存在')); 24 else reject('请求失败'); 25 }; 26 xhr.onerror = function() { 27 reject(this); 28 } 29 }) 30 }
获取数据的页面:
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <title>Document</title> 8 <script src="./ajax.js"></script> 9 </head> 10 11 <body> 12 13 </body> 14 <script> 15 let url = 'https://result.eolinker.com/9ADUI9L779d8c4e34cc40db1d6a5d9bd9284d85d7dd8b14?uri=getTest'; 16 request(url) 17 .then(result => { 18 console.log(result); 19 //可以对获取的数据进行处理,然后再发送ajax请求 --根据逻辑来进行层次处理 --利用return来实现 20 return request(url); 21 }, null) 22 .then(result => { 23 console.log(result); 24 }) 25 .catch(err => { //来捕获可能出现的异常 26 console.log(err) 27 }); 28 </script> 29 30 </html>
//执行结果
身是红尘雨中客,
愿有执伞并肩人.