【问题标题】:Display a response from a Fetch with HTML?使用 HTML 显示来自 Fetch 的响应?
【发布时间】:2020-09-27 18:26:38
【问题描述】:

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

我的 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>

背景和细节:

  • 我做过一些移动开发,但我是一个菜鸟,甚至在网络上也有基本的 HTML/JS 交互,所以我的知识有一些漏洞
  • 我将在 Squarespace(Adirondack 模板,Adirondack 系列)上将此代码注入实现为代码块,但我认为 Squarespace 上下文无关紧要(Fetch 工作正常,并且代码注入已显示其他的就好)
  • 我的尝试出错:VM22305 about:srcdoc:8 Uncaught (in promise) TypeError: Cannot read property 'events' of undefined
  • 我不致力于任何特定的显示方式,我只是想通过在页面上看到一些东西来让球滚动

感谢您的帮助!

【问题讨论】:

  • 记录响应信息的.then() 回调不返回值。如果你只是删除 .then() 它应该可以工作。
  • 谢谢@Pointy。我想我没有足够的分数来支持你的评论,但你的意见很有帮助

标签: javascript html response fetch-api


【解决方案1】:

您的第二个then 是控制台日志记录并且不返回任何内容(console.log 返回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>

它应该可以工作。

【讨论】:

  • 感谢@Elias。从您的回答和@Pointy 的评论中,我可以看到我可以通过返回一个值并处理已返回的内容来处理数据,或者通过删除第二个.then() 来更直接地处理数据
【解决方案2】:

如果你想要一个 then 链,你需要返回一个 promise 给下一个,像这样:

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;
        });

【讨论】:

    猜你喜欢
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    • 2017-01-09
    • 1970-01-01
    • 2019-11-11
    • 1970-01-01
    相关资源
    最近更新 更多