首页 > 解决方案 > 在 html 中使用 fetch api

问题描述

fetch关于在 html 文件中的使用,我有一个简单的问题。

我在 AWS Api Gateway 中创建了一个 API,它有一个简单的 GET 方法:GET 方法返回一个 json。

现在,如果我直接访问或使用邮递员访问我的方法的链接,它可以正常工作,但是当我尝试使用fetch错误时,会发生错误并且我看不到任何结果。

我在互联网上搜索,因为我既不知道 javascript 也不知道 html,但我找不到如何使它正常工作。例如,我在下面的代码中尝试做的是将通过 GET 获取的 json 放入标签中。

这是我的 html 文件:

<!DOCTYPE html>
<html>
   <head>
      <meta http-equiv="content-type" content="text/html; charset=UTF-8">
      <title>test.html</title>
   </head>
   <body>
      <dl>
         <dt>Page 1</dt>
         <dd>Go to <a href="https://xxx.execute-api.eu-central- 
   1.amazonaws.com/prod/getcustomerdetailsbyemail/">link</a></dd>
      </dl>
      <p> <input name="Button" value="Click me" onclick="buttonClick()" type="button">&nbsp;<input
         name="Button2" value="Click me 2" formmethod="get" onclick="buttonClick2()" type="button">
      </p>
      <p> <input id="myText" name="Message" value="Insert text" type="text"></p>
      <label for="myText" id="mylabel"></label>
      <div id="myData"> </div>
      <dl>
      </dl>
      <dl>
      </dl>
      <script type="text/javascript">
         function buttonClick(){
            alert(document.getElementById("myText").value);
         }
      </script>
      <script type="text/javascript">
         function buttonClick2(){
          fetch("https://xxx.execute-api.eu-central-1.amazonaws.com/prod/getcustomerdetailsbyemail")
           .then(response => {
               document.getElementById("mylabel").value = response.json();
           })
           .catch(error => {
               alert("Nope");
           });
      </script>
   </body>
</html>

如何将 get 调用返回的 json 放入标签中?

我还有一个问题:如果我 console.log("message")在 html 文件中放入一个脚本,那么当脚本运行时我会发生什么?(剧透:什么都没发生,为什么?)

如果我忽略了一些重要的事情,我很抱歉,但我不知道从哪里开始。

标签: javascripthtmlfetch-api

解决方案


问题是response.json()产生一个Promise,所以你需要等待它解决并使用结果:

function buttonClick2(){
  fetch("https://your-url.com")
   .then(response => response.json()) // <-- important line
   .then(response => {
       // changed .value to .innerHTML but you can handle it as you wish
       document.getElementById("mylabel").innerHTML = response;
   })
   .catch(error => {
       alert("Nope");
   });
}

在这里您可以通过示例查看Body.json()的文档


推荐阅读