ES6 Promise

 1 function ajax(type,url,data){
 2     var xhr;
 3     if(XMLHttpRequest){
 4         xhr = new XMLHttpRequest();
 5     }else{
 6         xhr = new ActiveXObject("MicroSoft.XMLHttp");
 7     }
 8     return new Promise(function(resolve,reject){
 9         xhr.onreadystatechange = function(){
10             if(xhr.readyState===4){
11                 if(xhr.status===200){
12                     resolve(xhr.response);
13                 }else{
14                     reject(xhr.status);
15                 }
16             }
17         }
18         xhr.open(type,url,true);
19         xhr.responseType = "json";
20         if(type=="get"||type=="GET")
21         {
22              xhr.send();
23         }else{
24              xhr.setRequestHeader("Content-Type","application/json");
25              xhr.send(JSON.stringify(data));
26         }
27     })
28 }

 

posted @ 2018-06-12 14:35  小小Developer  阅读(65)  评论(0)    收藏  举报