为什么在拨打 api 电话时,我的 html 中有 "undefined" 文本
Why is there "undefined" text in my html when making an api call
任何人都可以告诉我为什么在我进行此 api 调用时 HTML 中出现未定义的文本吗?控制台中没有错误。我对使用 apis 有点陌生,所以任何建议都会有所帮助。谢谢!
以下是我打电话的方式:
// Load list of blog posts
window.onload = function() {
fetch('https://jsonplaceholder.typicode.com/posts?userId=1')
.then((response) => response.json())
.then((posts) => {
let output;
posts.forEach(function(post) {
output += `
<li class="post">
<h2><a href="#" target="_blank">${post.title}</a></h2>
<p>${post.body}</p>
</li>
`
});
document.querySelector('#posts').innerHTML = output;
});
};
这是输出的可视图像
Screenshot
在连接之前先用空字符串初始化输出变量。
let output = "";
任何人都可以告诉我为什么在我进行此 api 调用时 HTML 中出现未定义的文本吗?控制台中没有错误。我对使用 apis 有点陌生,所以任何建议都会有所帮助。谢谢!
以下是我打电话的方式:
// Load list of blog posts
window.onload = function() {
fetch('https://jsonplaceholder.typicode.com/posts?userId=1')
.then((response) => response.json())
.then((posts) => {
let output;
posts.forEach(function(post) {
output += `
<li class="post">
<h2><a href="#" target="_blank">${post.title}</a></h2>
<p>${post.body}</p>
</li>
`
});
document.querySelector('#posts').innerHTML = output;
});
};
这是输出的可视图像 Screenshot
在连接之前先用空字符串初始化输出变量。
let output = "";