用promise封裝ajax


首先貼代碼

 1 var ajaxOptions = {
 2     url: 'url',
 3     method: 'GET',
 4     async: true,
 5     data: null,
 6     dataType: 'text',
 7 }
 8 
 9 function ajax(protoOptions) {
10     var options = {};
11 
12     for(var i in ajaxOptions){
13         options[i] = protoOptions[i] || ajaxOptions[i];
14     }
15     
16 
17     return new Promise(function(resolve, reject){
18         var xhr = new XMLHttpRequest();
19 
20         xhr.open(options.method, options.url, options.async);
21 
22         xhr.onreadystatechange = function() {
23             if (this.readyState === 4 && this.status === 200) {
24                 resolve(this.responseText, this);
25             } else {
26                 var resJson = {
27                     code: this.status,
28                     response: this.response
29                 }
30                 reject(resJson, this)
31             }
32         }
33 
34         xhr.send()
35 
36     })
37 }

注釋:

1,open(method, url, async) 

  method:  GET和POST;

  url: 發送到服務端的url;

  async: 異步true,同步false;

2,onreadystatechange

  每當readyState的值變化,onreadystatechange函數自動執行

3,readyState 服務器響應的狀態信息

  

  • 0: 請求未初始化
  • 1: 服務器連接已建立
  • 2: 請求已接收
  • 3: 請求處理中
  • 4: 請求已完成,且響應已就緒

  當readyState的值為4,status狀態為200時表示相應已就緒,可以執行成功調用的方法,反之調用失敗調用的方法

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM