Hi there!
I am working on my first JSON page, a simple FAQ page (Question & Answer). I have been watching Tutorials on Youtube on how to import data to an HTML page, but getting confused …
Could you please explain how to do this? I m not looking for a solution but I want to learn.
Have a look at code:
JSON:
[
{
"title": "how to eat healthy?",
"answer": "Do no eat junk food!"
},
{
"title": "how to relax?",
"answer": "Go to grab a coffee"
}
]
The file (JSON) is external, so I should use “fetch” - Could you please a tutorial on where to learn step-by-step? …or any online resource you think will help me.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="faq.json" type="application/json"></script>
<!-- Uncoment the line below if you use a file JS and comment ore delete the tag <script>And the code</script> in the body -->
<!-- <script src="./main.js"></script> -->
<title>FAQ</title>
</head>
<body>
<!-- START JS: This code can go in a main.js file located in the same folder, calling in the head <script src="./main.js"></script> -->
<script>
//Event on ready DOM
document.addEventListener("DOMContentLoaded", function () {
//Fetch data
fetch('./faq.json')
.then((response) => response.json())
.then((json) => {
//Then json info is here
console.log(json);
//You can play here doing a loop and using de iterator "i" for make it at one.
//Example: document.querySelector(".faq--0" + i + "h1").innerHTML = json[0].title;
//Example: document.querySelector(".faq--0" + i + " p").innerHTML = json[0].answer;
document.querySelector(".faq--01 h1").innerHTML = json[0].title;
document.querySelector(".faq--01 p").innerHTML = json[0].answer;
})
});
</script>
<!-- END JS-->
<!-- START Content HTML -->
<div class="faq--container">
<section class="faq--01">
<h1></h1>
<p></p>
</section>
<section class="faq--02">
<h1></h1>
<p></p>
</section>
</div>
<!-- END Content HTML -->
</body>
</html>
Thank you so much! That’s what I was looking for. I have been google it but and I wasn’t able to code by my self. I am now study the code in order to understand line by line the logic.
If you want to improve and try more things with this, I recommend you to look at this, to understand what I have used.
<==========================================>
<==========================================>
Events (Why used document.addEventListener(“DOMContentLoaded”, function () {)
This event, waits first to DOM content loaded and then do something.
You can check more events, there are a lot of them. (“click” for example).
[ {"key": "values", "key": "values"},...............]
[] // => Array object ==> Every item array has a position 0 to the end of array, in this case, the first one is [0] position.
{} //=> Object ==> Access data with selecting keys (title and answer)