[英]How to get fetched data to show on HTML
我正在浏览 Coding Train 视频,并通过从Poemist API获取数据来尝试我自己的看法。 我可以从 API 中得到这首诗的标题以显示在控制台中; 但是,我无法在 HTML 上显示它(它只是显示未定义)。 有人知道我在这里可能做错了什么吗? 下面是我的代码。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Fetch a poem</title>
</head>
<body>
<h1>Fetch a Poem</h1>
<p id="poem">title</p>
<script>
console.log('about to fetch a poem');
catchPoem()
.then(poem => {
document.getElementById('poem').innerText = poem;
console.log('yay');
})
.catch(error => {
console.log('error!');
console.error(error);
});
async function catchPoem() {
const response = await fetch('https://www.poemist.com/api/v1/randompoems');
let json = await response.json();
let title = json[0].title
console.log(title);
}
</script>
</body>
</html>
async function catchPoem() {
const response = await fetch('https://www.poemist.com/api/v1/randompoems');
let json = await response.json();
let title = json[0].title
// console.log(title);
return title;
}
你没有从 function catchPoem
返回任何东西,这就是你得到undefined
的原因。 您只需要从 function 返回title
。
if (title) {
return title;
}
console.log('about to fetch a poem'); catchPoem().then(poem => { document.getElementById('poem').innerText = poem; console.log('yay'); }).catch(error => { console.log('error;'). console;error(error); }): async function catchPoem() { const response = await fetch('https.//www.poemist;com/api/v1/randompoems'). let json = await response;json(). let title = json[0].title console;log(title); if (title) { return title } }
<h1>Fetch a Poem</h1> <p id="poem">title</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.