使用ajax请求接口

181 阅读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>
    <script>
      // 接口地址
      //   https://api.vvhan.com/api/la.ji?lj=%E7%85%A7%E7%89%87  //
      // 定义url
      const url = "https://api.vvhan.com/api/la.ji?lj=%E7%85%A7%E7%89%87";
      //   开始用ajax,浏览器和服务器异步通信
      // 先用new创建xhr对象,下面全部要xhr加点调用
      const xhr = new XMLHttpRequest();
      // 为xhr添加事件监听
      xhr.onreadystatechange = () => {
        // 判断全部数据是否返回
        if (xhr.readyState !== 4) {
          // 直接不往下走
          return false;
        }
        // 如果能走到这一步,判断状态码
        if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
          // 打印响应数据
          console.log("数据请求成功");
          console.log(xhr.responseText);
        }
      };
      // 定义open
      xhr.open("GET", url, true);
      // 定义send
      xhr.send(null);
    </script>
  </body>
</html>