使用 HTML 显示来自 Fetch 的响应?

Display a response from a Fetch with HTML?

我的目标是在网页上显示一些数据,这些数据是我使用 HTML 通过 Fetch 获得的。

我的 Fetch(有效)看起来像这样

<script>
  let response = fetch(
    "https://api.seatgeek.com/2/events?per_page=100&venue.city=boston&client_id=MYAPIKEY"
  )
    .then((response) => response.json())
    .then((response) => console.log(response.events[0].title));
</script> 

代码有效,并按照我的要求向控制台记录响应。现在,我想在我的网页上显示一些回复。

我的尝试看起来像这样

<center><h2 id="response"></h2></center>    
<script>
      let response = fetch(
        "https://api.seatgeek.com/2/events?per_page=100&venue.city=boston&client_id=MYAPIKEY"
      )
        .then((response) => response.json())
        .then((response) => console.log(response.events[0].title))
        .then((response) => {
          document.getElementById("response").innerHTML = response.events[0].title;
        });
    </script>

上下文和详细信息:

感谢您的帮助!

您的第二个 then 是控制台日志记录并且不返回任何内容(console.log returns undefined),因此在下一个 then 语句中 responseundefined.

将您的代码更改为:

<center><h2 id="response"></h2></center>    
<script>
      let response = fetch(
        "https://api.seatgeek.com/2/events?per_page=100&venue.city=boston&client_id=MYAPIKEY"
      )
        .then((response) => response.json())
        .then((response) => {
          console.log(response.events[0].title);
          return response;
        })
        .then((response) => {
          document.getElementById("response").innerHTML = response.events[0].title;
        });
</script>

它应该可以工作。

如果你想要一个 thens 链,你需要 return 对下一个的承诺,就像这样:

let response = fetch(
        "https://api.seatgeek.com/2/events?per_page=100&venue.city=boston&client_id=MYAPIKEY"
      )
        .then((response) => response.json())
        .then((response) => {
          document.getElementById("response").innerHTML = response.events[0].title;
        });