6、Promise实践练习-ajax请求

138 阅读1分钟
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <button id="btn">点击发送ajax请求</button>
  <script>
    //接口 https://api.apiopen.top/getJoke

    const btn = document.querySelector("#btn")
    btn.addEventListener("click", function(){

      const url = "https://v.juhe.cn/toutiao/index?type=top&key=93fc7c3e3c052ba9839763f55859b7dc"
      //1、创建对象
      const xhr = new XMLHttpRequest()

      //2、初始化
      xhr.open("GET", url)

      //3、发送
      xhr.send()

      //4、处理响应结果
      xhr.onreadystatechange = function(){
        if(xhr.readyState === 4){
          //判断响应状态吗 2xx
          if(xhr.status >= 200 && xhr.status < 300){
            //控制台输出响应体
            console.log(xhr.response)
          }
          else{
            //控制台输出响应状态吗
            console.log(xhr.status)
          }
        }
      }
    })
  </script>
</body>
</html>

用Promise进行封装

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <button id="btn">点击发送ajax请求</button>
  <script>
    //接口 https://api.apiopen.top/getJoke

    const btn = document.querySelector("#btn")
    btn.addEventListener("click", function(){

      const p = new Promise((resolve, reject) => {
        const url = "https://v.juhe.cn/toutiao/index?type=top&key=93fc7c3e3c052ba9839763f55859b7dc"
        //1、创建对象
        const xhr = new XMLHttpRequest()

        //2、初始化
        xhr.open("GET", url)

        //3、发送
        xhr.send()

        //4、处理响应结果
        xhr.onreadystatechange = function(){
          if(xhr.readyState === 4){
            //判断响应状态吗 2xx
            if(xhr.status >= 200 && xhr.status < 300){
              //控制台输出响应体
              resolve(xhr.response)
              //console.log(xhr.response)
            }
            else{
              reject(xhr.status)
              //控制台输出响应状态吗
              //console.log(xhr.status)
            }
          }
        }
      })

      //调用then方法
      p.then(value=>{
        console.log(value)
      }, reason=>{
        console.log(reason)
      })
    })
  </script>
</body>
</html>