如何将包含HTML的JSON解析为HTML

时间:2022-09-04 09:04:56

I want to parse a JSON object response.indexText which contains HTML tags (validated with JSONLint).

我想解析JSON对象响应。包含HTML标签的索引文本(使用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.)

进入

但当我使用时(在第一个答案后编辑)。窗口。onload inside和outside不会改变问题。

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?

重新载入页面,它将是空的。什么错了吗?如何解析JSON内容,以便客户机将内容呈现为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.

我想做的。目前我的页面由多个*组成。html文件。所有页面都有相同的导航栏和相同的页脚。只有内容会改变。现在,我正在尝试在JSON文件中存储内容,以便在单击导航链接时更改文本。

1 个解决方案

#1


1  

Put your code inside window.onload and you will get your required result.

将代码放在窗口中。onload,您将得到所需的结果。

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/

使用JSfiddle: https://jsfiddle.net/y2rkhp8g/1/。

#1


1  

Put your code inside window.onload and you will get your required result.

将代码放在窗口中。onload,您将得到所需的结果。

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/

使用JSfiddle: https://jsfiddle.net/y2rkhp8g/1/。