使用promise封装Ajax

一、封装Ajax

  1 <script>
  2         var ajax = new Promise((resolve, reject) => {
  3             var xhr = new XMLHttpRequest();
  4             xhr.open('get', './test1.txt', true);
  5             xhr.send();
  6             xhr.onreadystatechange = function() {
  7                 if (xhr.status == 200 && xhr.readyState == 4) {
  8                     resolve(xhr.responseText);
  9                 }
 10                 setTimeout(function() {
 11                     reject(new Error('连接超时'));
 12                 }, 2000);
 13             }
 14         });
 15 
 16         ajax.then(function(data) {
 17             console.log(data);
 18         }).catch(function(err) {
 19             console.error(err);
 20         })
 21     </script>

二、封装get请求

  1     <script>
  2         function $get(url, data) {
  3             if (typeof data === 'object') {
  4                 url += "?time=" + Date.now();
  5                 for (var i in data) {
  6                     url += "&" + i + "=" + data[i];
  7                 }
  8             }
  9             return new Promise((resolve, reject) => {
 10                 var xhr = new XMLHttpRequest();
 11                 xhr.open('get', url, true);
 12                 xhr.send();
 13                 xhr.onreadystatechange = function() {
 14                     if (xhr.readyState == 4 && xhr.status == 200) {
 15                         resolve(xhr.responseText);
 16                     }
 17                     setTimeout(() => {
 18                         reject(new Error('连接超时'));
 19                     }, 2000);
 20                 }
 21             });
 22         }
 23 
 24         $get('./test.txt', {
 25             "username": "zhansgan"
 26         }).then(function(data) {
 27             console.log(data);
 28         }).catch(function(err) {
 29             console.error(err);
 30         })
 31     </script>
posted @ 2019-10-22 11:35  大把小米  阅读(1140)  评论(0编辑  收藏  举报