用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时表示相应已就绪,可以执行成功调用的方法,反之调用失败调用的方法

  

原文地址:https://www.cnblogs.com/zhangbs/p/9674826.html