• 使用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>
    每天都要努力微笑,努力学习,每一天都要对得起自己。
  • 相关阅读:
    香港2013迷你制汇节即将启幕
    neuroph轻量级神经网络框架
    java如何实现python的urllib.quote(str,safe='/')
    python 的日志logging模块
    Python 代码使用pdb调试技巧
    python中reload(module)的用法,以及错误提示
    Notepad++如何取消打开最近的历史文件
    机器学习--入门答疑
    计算机的启动过程
    缓存设计
  • 原文地址:https://www.cnblogs.com/likecn/p/11718838.html
Copyright © 2020-2023  润新知