Reputation: 603
I want to parse a JSON object response.indexText
which contains HTML tags (validated with JSONLint).
{
"indexText": "<div id=\"content-home\"><h1> Hello World! <\/h1> <p>Some text.<\/p><p>Some more text.<\/p></div>"
}
into <div id="indexText"></div>
But when I use (EDIT after first answer. window.onload inside and outside does not change the problem.)
window.onload = function () {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let response = JSON.parse(xhttp.responseText);
document.getElementById("indexText").innerHTML = response.indexText;
}
};
xhttp.open("GET", "./json/en.json", true);
xhttp.send();
};
and reload the page it will be empty. What is going wrong? How can I parse the JSON content such that the client will render the content as HTML?
What I am trying to do. At the moment my page consists of multiple *.html files. All pages have the same navigation bar and the same footer. Only the content does change. Now I am trying to store the content inside of my JSON file such that I can change the text when clicking navigation links.
Upvotes: 2
Views: 3194
Reputation: 21756
Put your code inside window.onload and you will get your required result.
Check the below working code:
window.onload = function() {
var response = {
"indexText": "<div id=\"content-home\"><h1> Hello World! <\/h1> <p>Some text.<\/p><p>Some more text.<\/p></div>"
};
document.getElementById("indexText").innerHTML = response.indexText;
};
<div id="indexText"></div>
Working JSfiddle here : https://jsfiddle.net/y2rkhp8g/1/
Upvotes: 1