Home > Software engineering >  Random text on page reloading
Random text on page reloading

Time:08-31

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 >
  <h3 >A Piece of Book</h3>
  <div >
    <p >
      “It is only with the heart that one can see rightly; what is essential
      is invisible to the eye.”
    </p>
    <div >
      <p >Antoine de Saint-Exupéry</p>
      <p >The Little Prince</p>
    </div>
  </div>
</section>

how can do it?

CodePudding user response:

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.

CodePudding user response:

1 - Read JSON file array of objects.

let quotes = [{
    author: "xxx",
    quote: "xxx",
    bookName: "xxx" }]; // created from JSON or from any API

2 - use Math.Random and select one object from the quotes array.

let selectedQuote = quotes[Math.floor(Math.random()*quotes.length)];

3 - use this selectedQuote object and bind it to your HTML, onl oad at body tag would be a good starting point.

CodePudding user response:

What about using ajax? You can use $.ajax() to send ajax requests if you're using jQuery. If you use only javascript, you could use XHR object to send ajax requests. Here's the simple code using jQuery below.

$.ajax(
    json_url,
    dataType: 'json',
    success: function(data) {
        $('.piece_book--text').html(data.book_text);
        ...
    }
);

You can see more about $.ajax on jQuery API Document.

CodePudding user response:

First you need array of quotes. Then you need to select random quote from array on load.

Here is working example:

var quoteArray = [
    '“Quote N 1“',
    '“Quote N 2“',
    '“Quote N 3“',
    '“Quote N 4“',
    '“Quote N 5“'
];
var randomNumber = Math.floor(Math.random() * quoteArray.length);

window.addEventListener('load', (event) => {
  document.getElementsByClassName("piece_book--text")[0].innerHTML = quoteArray[randomNumber];
});
<section >
  <h3 >A Piece of Book</h3>
  <div >
    <p ></p>
    <div >
      <p >Antoine de Saint-Exupéry</p>
      <p >The Little Prince</p>
    </div>
  </div>
</section>

  • Related