zoukankan      html  css  js  c++  java
  • Promise封装AJAX

     1         // // 创建对象
     2         // const xhr = new XMLHttpRequest();
     3         // // 初始化访问方式和地址
     4         // xhr.open('get', 'https://api.apiopen.top/getJoke');
     5         // //发送访问请求
     6         // xhr.send();
     7         // //绑定事件接收并处理响应结果
     8         // xhr.onreadystatechange = () => {
     9         //     if(xhr.readyState===4){
    10         //         //如果返回的状态码在200-300之间
    11         //         if(xhr.status>=200&&xhr.status<300){
    12         //             // 表示成功,输入响应结果
    13         //             console.log(xhr.response)
    14         //         }else{
    15         //             // 如果失败,返回错误状态码
    16         //             console.log(xhr.status)
    17         //         }
    18         //     }
    19         // }
    20 
    21         // 使用Promise封装XMLHttpRequest
    22         const p = new Promise((reslove, reject) => {
    23             setTimeout(() => {
    24                 // 创建对象
    25                 const xhr = new XMLHttpRequest()
    26                 // 声明访问方式和访问地址
    27                 xhr.open('get', 'https://api.apiopen.top/getJoke');
    28                 // 发送访问请求
    29                 xhr.send();
    30                 // 接收响应回调
    31                 xhr.onreadystatechange = () => {
    32                     // 与访问地址连接成功
    33                     if (xhr.readyState === 4) {
    34                         // 如果返回的状态码在200-300之间,表示成功响应
    35                         if (xhr.status >= 200 && xhr.status < 300) {
    36                             // 成功之后使用reslove接收返回的数据体
    37                             reslove(xhr.response)
    38                         } else {
    39                             // 否则使用 reject 接收错误码
    40                             reject(xhr.status)
    41                         }
    42                     }
    43                 }
    44             }, 1000);
    45 
    46         })
    47 
    48         // 声明结果的回调 then支持链式调用
    49         p.then(
    50             // (value)=>{} 成功的回调
    51             (value) => {
    52                 console.log(value)
    53             },
    54             // (reason)=>{} 错误的回调
    55             (reason) => {
    56                 console.log(reason)
    57             }
    58         )
  • 相关阅读:
    递归练习题1
    爬虫模块之Beautiful Soup4
    python中的简易表格prettytable
    ubuntu中安装和使用quant-lib
    一个金融软件的基础功能分布
    ONLY_FULL_GROUP_BY 牛皮癣怎么治
    pandas
    pandas行筛选/列筛选(条件筛选/范围筛选)/计算
    conda 的 proxy设置
    openpyxl 安装失败的处理 (缺少 et_xmlfile )
  • 原文地址:https://www.cnblogs.com/zhh-blogs/p/15557493.html
Copyright © 2011-2022 走看看