我想解析一个 JSON 对象 response.indexText
其中包含 HTML 标签(使用 JSONLint 验证)。
{
"indexText": "<div id=\"content-home\"><h1> Hello World! <\/h1> <p>Some text.<\/p><p>Some more text.<\/p></div>"
}
进入<div id="indexText"></div>
但是当我使用时(在第一次回答后进行编辑。window.onload 内部和外部不会改变问题。)
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();
};
并重新载入页面,页面将为空。出了什么问题?我如何解析 JSON 内容,以便客户端将内容呈现为 HTML?
我正在尝试做什么。目前我的页面包含多个 *.html 文件。所有页面都有相同的导航栏和相同的页脚。只有内容会改变。现在我试图将内容存储在我的 JSON 文件中,这样我就可以在单击导航链接时更改文本。
最佳答案
把你的代码放在window.onload里面你会得到你需要的结果。
检查下面的工作代码:
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>
在这里工作 JSfiddle:https://jsfiddle.net/y2rkhp8g/1/
关于javascript - 如何将包含 HTML 的 JSON 解析为 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50949364/