基于promise的ajax封装

  1 //调用方式:
  2 /*
  3   ajaxPrmomise({
  4   url:,
  5   method:,
  6   headers:{}
  7 }).then(res=>{})
  8 */
  9 
 10 ;(function(window){
 11   //设置默认的参数配置项
 12   let _default = {
 13     url:'',
 14     baseURL:'',
 15     method:'GET',
 16     params:null, //get请求基于问号传参方式传递给服务器的内容
 17     headers:{},
 18     timeout:500,
 19     dataType:'json',
 20     data:null,  //post请求基于请求主体传参方式传递给服务器的内容
 21     cache:true   //是否缓存数据
 22   };
 23   //resolve,reject,response,fn
 24   let _setResponseMsg = function _setResponseMsg(...rest){
 25       let [
 26         resolve,
 27         reject,
 28         xhr,
 29         fn
 30       ] = rest,
 31       res = null,
 32       response = xhr;
 33       res.data = fn(response.responseText);
 34       res.status = response.status;
 35       res.statusText = response.statusText;
 36       res.xhr = response;
 37       res.headers = response.getAllResponseHeaders();
 38       resolve(res)
 39   }
 40 
 41   let _convertJSON = function _convertJSON(result){
 42       let data = "";
 43       try {
 44         data = JSON.parse(result);
 45       } catch (e) {
 46         reject(e)
 47       }
 48       return data
 49   }
 50 
 51   let _convertString = function _convertString(result){
 52       return result;
 53   }
 54 
 55   let _array_to_str = function _array_to_str(key,arr){
 56       let params = "";
 57       for(let i0;i<arr.length;i++){
 58         params += `${key}=${arr[i]}&`;
 59       }
 60       return params.slice(0,-1)
 61   }
 62 
 63   let _convertParams = function _convertParams(cache,params){
 64     let str = "?",
 65         time_str = cache ? "":(+(new Date())+"");
 66       if(typeof params == 'object' && Object.keys(params).length > 0){
 67           for(let key in params){
 68             if(typeof params[key] == 'object' && (length in params[key])){
 69               str += _array_to_str(key,params[key])
 70             }
 71             str += `${key}=${params[key]}`;
 72           }
 73       }
 74       return str+"&_="+time_str;
 75   }
 76 
 77   let _setHeader = function _setHeader(...res){
 78     let [xhr,headers] = res;
 79     for(let key in headers){
 80       if(headers.hasOwnProperty(key))
 81         xhr.setRequestHeader(key,headers[key])
 82     }
 83   }
 84 
 85   //基于promise管理ajax请求
 86   let ajaxPrmomise = function ajaxPrmomise(options={}){
 87       // 这里传递的options包含默认配置信息和用户基于暴露的_default修改后的信息
 88       for(let key in _default){
 89         if(key in options && _default.hasOwnProperty(key)){
 90             options[key] = _default[key]
 91         }
 92       }
 93       //=>这里可以写成
 94       options = {..._default,...options};
 95       let {
 96         url,
 97         method,
 98         baseURL,
 99         data,
100         dataType,
101         headers,
102         cache,
103         params
104       } = options;
105       let xhr,send_data;
106 
107       return new Promise((resolve,reject)=>{
108           xhr = new XMLHttpRequest();
109           _setHeader(xhr,headers);
110           send_data = method.toLowerCase() == 'get' ? _convertParams(cache,params):(method.toLowerCase() == 'post'? data:"");
111           all_url = baseURL + url + send_data;
112           xhr.open(method,all_url);
113           xhr.onreadystatechange = function(){
114             if(xhr.readyState == 4){
115               if(/^[23]\d{2}$/.test(xhr.status)){
116                   dataType = dataType.toUpperCase();
117                   if(dataType == "json")
118                     _setResponseMsg(resolve,reject,xhr,_convertJSON)
119                   _setResponseMsg(resolve,reject,xhr,_convertString)
120                 }
121               }
122             }
123             ajaxPrmomise.xhr = xhr;
124             xhr.send(send_data);
125           })
126       }
127   //修改默认配置,可以通过自己设置一些配置来覆盖默认配置
128   ajaxPrmomise.defaults = _default;
129 
130 ["get","head","options",""].forEach((method,indexs)=>{
131   ajaxPrmomise[method] = function(url,options){
132       return ajaxPrmomise({
133         ...options,
134         url:url,
135         method:method
136       })
137     }
138 });
139 ["post","put"].forEach((method,index)=>{
140   ajaxPrmomise[method] = function(url,data,options){
141     return ajaxPrmomise({
142       ...options,
143       url:url,
144       data:data,
145       method:method
146     })
147   }
148 })
149   window.ajaxPrmomise = ajaxPrmomise;
150 }(window))
View Code

 

打印: