[英]How to display all JSON Fetch API content on a HTML table using JavaScript
I'm starting to learn JavaScript, and i am having some difficulties for displaying the whole data i got from Json PlaceHolder fake API on my html table. I'm starting to learn JavaScript, and i am having some difficulties for displaying the whole data i got from Json PlaceHolder fake API on my html table. Using the code below i just manage to display the last element from the API itself, and not all elements as i wanted.
使用下面的代码,我只是设法显示 API 本身的最后一个元素,而不是我想要的所有元素。
Can someone help me figure it out how should i actually do?有人可以帮我弄清楚我应该怎么做吗?
There's the code:有代码:
fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => response.json())
.then((json) => json.forEach(tableElements)
)
function tableElements (element, index, arr){
arr[index] = document.querySelector('#posts-table tbody').innerHTML =
`<td>${element.userId}</td>
<td>${element.id}</td>
<td>${element.title}</td>
<td>${element.body}</td>`
}
Your code is showing one data because when the loop goes it are overwrites the previous one when it loop through the json, change the opperand to +=
and wrap the table columns with rows <tr>... </tr>
您的代码显示一个数据,因为当循环进行时,它会在循环通过 json 时覆盖前一个数据,将操作数更改为
+=
并用行<tr>... </tr>
包装表列
Try this code here在此处尝试此代码
fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => response.json())
.then((json) => json.forEach(tableElements)
)
function tableElements (element, index, arr){
arr[index] = document.querySelector('#posts-table tbody').innerHTML +=
`<tr>
<td>${element.userId}</td>
<td>${element.id}</td>
<td>${element.title}</td>
<td>${element.body}</td>
</tr>`
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.