add articles from multiples html files using javascript

I am trying to build some site, I have index.html page and I want to load it a section (article section) from another page that stored local in my library

What I have so far is this:

  <body>
      </header>
      <main>
      <div class="container">
        <div id="demo">
        <div>
      </div>
   <script src="./scripts/onload.js" charset="utf-8"></script>
  </header>
  </body>

in onload.js I have the code as follow:

function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("GET", "./first/Prophet-Riddles-App-update.html", true);
  xhttp.send();
}
window.addEventListener("load",loadDoc);

so far it's working and it load my Prophet-Riddles-App-update.html to index.html, but want I need is to load multiple file and if I am going in this way, say setup the function twice... it doesn't work.

can anyone please help? what it the best way to achieve that?

Answers 1

  • You should refactor your loader to load file that is given as argument so you will be able to reuse it:

    function loadDoc(url, target) {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          document.getElementById(target).innerHTML =
          this.responseText;
        }
      };
      xhttp.open("GET", url, true);
      xhttp.send();
    }
    
    function loadAll() {
      loadDoc("./first/Prophet-Riddles-App-update.html", "demo");
      // ... repeat for other pages
    }
    window.addEventListener("load",loadAll);
    

Related Articles