0

I'm pretty new to JavaScript / TypeScript and I was writing this tiny piece of TS code to retreive the HTML from another page on my server and put it on a <div id='container'> tag.

let container = document.getElementById("container") as HTMLDivElement;
let req = new XMLHttpRequest();

function getContent(page: string): string {
    let content = "";
    const basePath = "content/";
    const url = basePath + page;
    
    req.open("GET", url);
    req.send();
    content = req.responseText;
    container.innerHTML = content;
    console.log(req.status);
    return content;
}

getContent('home'); 

Now, when I open the page on the browser (I'm using GitHub Pages for hosting) all I get is a blank page and a req.status of 0 in the console. Of course the file content/home.html exists. I tried both getContent('home') and getContent(home.html) but neither worked.

What am I doing wrong?

Thank you to all.

  • See [this answer](https://stackoverflow.com/a/26451773/1169519). – Teemu Apr 10 '22 at 10:09
  • The status is `0` because the request wasn't completed yet. `XMLHttpRequest` is async, you'll have to listen to events like `load` to get the actual `HTTP` status code of the response. [More details](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest) – Titus Apr 10 '22 at 10:17

0 Answers0