I have
/mysite/index.html
Then I have a folder /mysite/products/ with JSON files as following:
/mysite/products/1.json
/mysite/products/2.json
/mysite/products/3.json
...
/mysite/products/578.json
and etc…
Every JSON file looks like this:
[{"id":1,"name":"16' Tire Japan","stock":145}]
In my HTML I have a table:
<table>
<thead>
<th>id</th>
<th>name</th>
<th>stock</th>
</thead>
<tbody id="products"></tbody>
</table>
Then I have a file /mysite/script.html
connected with my HTML.
How can I fetch all existing .JSON
files one by one from my /products folder into the table tbody (id=products)
using JavaScript?
Now I have one JSON file for all products and I use fetch() like this:
fetch("products.json")
.then(function(response) {
return response.json();
})
.then(function(products){
let placeholder = document.querySelector("#products");
let out = "";
for(let product of products){
out += `<tr id='tr${product.id}'>
<td class='id'>${product.id}</td>
<td class='name'>${product.name}</td>
<td class='stock'>${product.stock}</td>
</tr>`;
}
placeholder.innerHTML = out;
});
2
Answers
First of all you need to store somewhere information about all your "/mysite/products/*.json" files.
A. You can hardcode it in your script
B. ..or you can download it remotely.
Then you can download all your files:
A. One by One
B. … or you can do that simultaneously with Promise.all(array_of_fetch)
Then you can do your part of code "let placeholder = …" to populate your table
Pleaes note that many browser has only 6-12 allowed connections and it can take quite long time to download 578 files.
Good luck with your project =)
maybe something like this
see also for await…of doc