使用fetch调用接口

103 阅读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>
    <style>
      p {
        font-weight: bold;
        font-size: 22px;
        color: orangered;
      }
    </style>
  </head>
  <body>
    <h1>每天一句土味情话</h1>
    <p></p>
  </body>
  <script>
    // 找到p标签
    const p = document.querySelector("p");
    // 定义一个url
    const url = "https://api.vvhan.com/api/love?type=json";
    // 使用fetch调用接口
    fetch(url)
      .then((response) => {
        response.json();
      })
      .then((json) => {
        p.innerHTML = json.ishan;
      })
      .catch((error) => {
        console.log(error);
      });
  </script>
</html>