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

标签 javascript html json web

我想解析一个 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/

相关文章:

javascript - 如何获得 google plus +1 按钮的计数器?

javascript - 我可以在 Firefox 扩展的弹出通知中设置背景颜色吗?

html - Css 隐藏 div 之外的红线(是一个跨度)?

html - 有什么方法可以使边框更接近正文内容? (HTML/CSS) 图片提供

C#/.Net - 解析 XML/XML 的快速方法 -> Json

javascript - 单击具有给定类的页面上的所有 anchor 标记,但在导航之前取消

javascript - Windows : Static files pending for up to two minutes? 上的 Node.js + Express.js

html - 如何通过在 div 绝对位置使用高度 100% 来显示完整图像高度?

python - 将来自 Python 的 Google map 地理编码器与 urllib2 结合使用

javascript - Extjs4 从树存储中保存 file.json