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>

  • 相关阅读:
    组播技术
    高阶函数
    《统计学习方法》第一章学习笔记
    R代码规范(转)
    数据挖掘与商业智慧:华通二十年专题----台湾辅仁大学谢邦昌教授访谈(转载)
    基于Hadoop的机器学习开源项目
    特征选择算法之开方检验(转载)
    朴素贝叶斯算法及不同特征值结果的比较
    走出数据挖掘的误区(转载)
    互联网时代的社会语言学:基于SNS的文本数据挖掘(转载)
  • 原文地址:https://www.cnblogs.com/weixin2623670713/p/13568477.html
Copyright © 2011-2022 走看看