My goal is to display random posts for clients visiting a static website. The information of these posts is stored in a json file on the server where all other html, css, js files are stored as well. The task can be splitted into three parts
- Generate the json file (done)
- Load data from the json file (partially done)
- Modify the html content (partially done)
The produced json on ./posts/posts.json:
{
"posts": [
{
"head": "Ship Post",
"text": "Just some text"
},
{
"head": "Holiday Post",
"text": "Text about holidays"
}
]
}
JavaScript code and html:
<div class="card">
<h2 id="rs-card-head-00"></h2>
<p id="rs-card-text-00"></p>
</div>
<script>
function change_title(){
var json = fetch("./posts/posts.json").then(response => {return response.json();});
document.getElementById('rs-card-head-00').innerHTML = json.posts[0].head;
document.getElementById('rs-card-text-00').innerHTML = json.posts[0].text;
}
change_title()
</script>
A similar script (replacing the html lines with console.log(json.posts[0].head)
and console.log(json.posts[0].text)
) works just fine in node.js
2
Answers
fetch
is asynchronous (it’s a promise that a request will be fulfilled or not) so you can’t assign the result to a variable because it will beundefined
at the point where you try to use its value.You have a couple of options.
Continuing to use
then
:Using
async/await
:Your code was missing the proper handling of promises. Fetch returns a promise and needs to be handled with then or async/await.
You need to handle the asynchronous nature of the fetch function. You can use async/await to wait for the response and then change the HTML