I can fetch the json data but I can't display it in HTML (javascript)

Viewed 76
<!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">
    </head>

    <body>
            <table class="table table-stripped">
                <tbody id="data">
    
                </tbody>
            </table> 
    
    
        <script>
            fetch("wig.json").then(
                res=>{
                    res.json().then(
                        data=>{
                            console.log(data);
                            if(data.length > 0){
                                var tmp = '';
                                data.forEach((u)=>{
                                    tmp +="<tr>";
                                    tmp += "<td>"+u.Name+"</td>";
                                    tmp += "<td>"+u.Oprice+"</td></tr>";
                                })
                                document.getElementById("data").innerHTML = tmp;
                            };
                        }
                    )
                }
            )
        </script>
    </body> 
</html>

I can fetch the local json data and I can see all my json data in the console. Yet. I can't display it using table and there is no any error statement shown. Can someone help me to fix this problem. I reference the code from:https://www.youtube.com/watch?v=WMQ2sq1dw6Y&t=230s

1 Answers

Hi i have created example for you but different source so i used json placeholder as source but the same approach of your code

fetch("https://jsonplaceholder.typicode.com/posts").then(res => {
  return res.json();
}).then(data => {
  console.log(data);
  if (data.length > 0) {
    let tmp = "";
    
    data.forEach(u => {
      tmp += `
        <tr>
          <td>${u.title}</td>
          <td>${u.body}</td>
        </tr>
      `
    });
    
    document.getElementById("data").innerHTML = tmp;
  }
});
<table class="table table-stripped">
  <tbody id="data">
  </tbody>
</table> 

You can use template literals to format your html string easily. I think the error on your code is the syntax near res.json you forgot to nest the brackets correctly.

If still not working check your data may be the casing of your json keys is not correct.

Related