简体   繁体   中英

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. Using the code below i just manage to display the last element from the API itself, and not all elements as i wanted.

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>
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>`
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM