i have section for book quotes like this.
see image
i want to replace new quote from json file with it’s own author and book name when the page is reloading.
it’s my code:
<section class="piece_book section">
<h3 class="piece_book--title">A Piece of Book</h3>
<div class="piece_box">
<p class="piece_book--text">
“It is only with the heart that one can see rightly; what is essential
is invisible to the eye.”
</p>
<div class="piece_book--info">
<p class="piece_book--author">Antoine de Saint-Exupéry</p>
<p class="piece_book--name">The Little Prince</p>
</div>
</div>
</section>
how can do it?
>Solution :
Well, if your JSON is an external file, you’ll need to fetch data, therefore show a loading animation while fetching the data with Ajax:
async function getJSONData() {
const data = await fetch('mydata.json');
const result = await data.json(); // i guess it's an array of quotes
// Chose one randomly:
const indexOfQuote = getRandomInt(0, result.length);
const quote = result[indexOfQuote];
// then according to the shape of your data, you will display
// what's need to be displayed by selecting the right elements
// Example:
const quoteElement = document.querySelector("#piece_book--text");
// and inserting the content:
quoteElement.textContent = quote.text; // for example
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
// function you can call like this:
getJSONData();
This in a script tag right before </body> in your HTML file.
More details on fetch on the MDN Documentation
Edit
You may get some trouble with CORS policy if you’re developing on a local file in your system. The option mode: 'no-cors' from fetch() does not fix the problem as we may think. It disables the warning but it doesn’t disable the protections. If you have any problem with that, use Live Server extension on Visual Studio Code, which will create a localhost which seems to be a more trusted environment lol.