需要引入的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>
//執行結果