zoukankan      html  css  js  c++  java
  • ES6-promise封装AJAX请求

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title></title>
    </head>
    <body>
    <!-- 方法一: -->
    <script>
    // 接口地址:https://api.apiopen.top/getJoke



    // 1.创建对象
    const xhr = new XMLHttpRequest();


    // 2.初始化
    //发 GET类型的请求 给这个接口发请求https://api.apiopen.top/getJoke
    // xhr.open("GET","https://api.apiopen.top/getJoke");表示成功
    // xhr.open("GET","https://api.apiopen.top/getJoke");
    // xhr.open("GET","https://api.apiopen.top/get"); 表示失败
    xhr.open("GET","https://api.apiopen.top/get");

    // 3.发送
    xhr.send();

    // 4.绑定事件,处理响应结果
    xhr.onreadystatechange=function(){
    // 对状态做出一个判断
    if(xhr.readyState===4){
    // 判断响应状态码 200-300 2系列的响应状态码都为成功
    if(xhr.status >= 200 && xhr.status <= 300){
    // 表示成功
    console.log(xhr.response);
    }else{
    // 如果失败
    console.error(xhr.status);
    }

    }
    }

    </script>



    <!-- 方法二: -->
    <script>
    // 接口地址:https://api.apiopen.top/getJoke


    const p = new Promise((resolve,reject)=>{
    // 1.创建对象
    const xhr = new XMLHttpRequest();


    // 2.初始化
    //发 GET类型的请求 给这个接口发请求https://api.apiopen.top/getJoke
    xhr.open("GET","https://api.apiopen.top/getJoke");

    // 3.发送
    xhr.send();

    // 4.绑定事件,处理响应结果
    xhr.onreadystatechange=function(){
    // 对状态做出一个判断
    if(xhr.readyState===4){
    // 判断响应状态码 200-300 2系列的响应状态码都为成功
    if(xhr.status >= 200 && xhr.status <= 300){
    // 表示成功 resolve修改promise的状态
    resolve(xhr.response);
    }else{
    // 如果失败
    reject(xhr.status);
    }

    }
    }
    })

    // 指定回调 结构清晰
    p.then(function(value){
    // 如果成功打印value
    console.log(value);
    },function(reason){
    console.log(reason);
    })
    </script>
    </body>
    </html>

  • 相关阅读:
    mongoDB安装配置
    linux-批量修改目录下后缀shell
    备份mysql的shell
    mysql_DML_索引、视图
    mysql_存储过程
    mysql_备份_mysqldump
    mysql_DCL_grant/revoke
    mysql_DML_select_子查询
    mysql_DML_select_union
    mysql_DML_select_聚合join
  • 原文地址:https://www.cnblogs.com/weixin2623670713/p/13568477.html
Copyright © 2011-2022 走看看