Reputation: 1
I'm a beginner and I'm wondering why my table won't populate with the information I'm trying to retrieve from the API. I've tried various methods of how to go about this and I'm stumped. I think I tried too many different ways and my brain is scrambled, probably overlooking something simple. Please let me know!
<h1>Nasa Facilities</h1>
<table id="table">
<thead></thead>
<tbody></tbody>
</table>
<script src="main.js"></script>
</body>
//Javascript--v
fetch('https://data.nasa.gov/resource/gvk9-iz74.json')
.then((res) => res.json())
.then((data) => {
let li = `<tr><th>Center</th><th>City</th><th>State</th><th>Weather</th></tr>`;
data.forEach((facility) => {
li += `<tr>
<td>${facility.center}</td>
<td>${facility.city} </td>
<td>${facility.state}</td>
<td>${facility.zipcode}</td>
</tr>`;
});
document.getElementById('table').innerText = li;
});
Upvotes: 0
Views: 2024
Reputation: 1094
Your code is overall correct, minor potential changes would be to have a variable for headers and one for rows when setting the innerHTML of headers and table rows.
You need to put javascript in tag or move it to another js file.
Also added document.addEventListener("DOMContentLoaded") which means the js code is executed after the table is loaded.
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<h1>Nasa Facilities</h1>
<table id="table">
<thead></thead>
<tbody></tbody>
</table>
</body>
<script>
document.addEventListener("DOMContentLoaded", function () {
fetch("https://data.nasa.gov/resource/gvk9-iz74.json")
.then((res) => res.json())
.then((data) => {
let headers = `
<tr>
<th>Center</th>
<th>City</th>
<th>State</th>
<th>Weather</th>
</tr>`;
document.querySelector("thead").innerHTML = headers;
let rows = "";
data.forEach((facility) => {
rows += `
<tr>
<td>${facility.center}</td>
<td>${facility.city} </td>
<td>${facility.state}</td>
<td>${facility.zipcode}</td>
</tr>
`;
});
document.querySelector("tbody").innerHTML = rows;
});
});
</script>
</html>
Upvotes: 2