<script>
// Fetch JSON data
fetch('dat.json')
.then(response => response.json())
.then(data => {
const tbody = document.querySelector('#dataTable tbody');
data.forEach(item => {
const row = document.createElement('tr');
row.innerHTML = `
<td>${item.name}</td>
<td>${item.age}</td>
<td>${item.city}</td>
`;
tbody.appendChild(row);
});
})
.catch(error =>console.error('Error fetching the data:', error));
</script>
why json file value is not displayed the code i took from chatgpt i tried vscode and notepad +++ too none of them work.
2
Answers
First, check the location of the JSON file.
If dat.json is in the same folder as the HTML file, the fetch path should be ‘./dat.json’.
If it’s in a subfolder, the path should reflect that, e.g., ‘./data/dat.json’.
The return value may not be suitable for an array method. forEach is an array method, if there is no suitable structure for it, it will not be displayed in the interface as it will return an error. details: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
For example, when I request
https://jsonplaceholder.typicode.com/todos/1
point, I cannot use the array method for this response. But when I get thehttps://jsonplaceholder.typicode.com/todos/
items, I can now use the array methods.First, check the return values from the ‘dat.json’ request from the http requests. Then you can convert the values from the request into a suitable structure for the array.