我的目标是在网页上显示一些数据,这些数据是我使用 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>
背景和细节:
- 我做过一些移动开发,但我是一个菜鸟,甚至连基本的 HTML/JS 网络交互都不懂,所以我的知识存在一些漏洞
- 我将将此代码注入(inject)实现为 Squarespace(Adirondack 模板、Adirondack 系列)上的代码块,但我认为 Squarespace 上下文并不重要(Fetch 工作得很好,并且代码注入(inject)一直显示其他的都还好)
- 我的尝试出错:
VM22305 about:srcdoc:8 Uncaught( promise )TypeError:无法读取未定义的属性“事件”
- 我不致力于任何特定的显示方式,我只是想通过查看页面上的内容来让事情顺利进行
感谢您的帮助!
最佳答案
您的第二个 then
是控制台日志记录,并且不返回任何内容(console.log 返回 undefined
),因此在下一个 then
语句中 响应
是未定义
。
将代码更改为:
<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>
它应该可以工作。
关于javascript - 使用 HTML 显示 Fetch 的响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62267998/