zoukankan      html  css  js  c++  java
  • 使用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>
    每天都要努力微笑,努力学习,每一天都要对得起自己。
  • 相关阅读:
    OO第四次暨期末总结
    OO第九到十一次作业小结
    OO第五到七次作业小结
    OO前三次作业阶段小结
    数据预处理相关
    Latex+VScode安装
    python学习网站+查询网站
    arcgis画图中添加带箭头的直线
    在ArcGIS 中标注中竖排文字
    vs2015使用fopen时遇到unsafe问题
  • 原文地址:https://www.cnblogs.com/likecn/p/11718838.html
Copyright © 2011-2022 走看看