【问题标题】:How to parse JSON containing HTML as HTML如何将包含 HTML 的 JSON 解析为 HTML
【发布时间】:2018-06-21 12:08:29
【问题描述】:

我想解析一个 JSON 对象 response.indexText,其中包含 HTML 标签(使用 JSONLint 验证)。

{
  "indexText": "<div id=\"content-home\"><h1> Hello World! <\/h1> <p>Some text.<\/p><p>Some more text.<\/p></div>"
}

进入&lt;div id="indexText"&gt;&lt;/div&gt; 但是当我使用 (EDIT after first answer.window.onload inside and 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();  
}; 

并且重新加载页面,它将是空的。出了什么问题?如何解析 JSON 内容,以便客户端将内容呈现为 HTML?

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

【问题讨论】:

    标签: javascript html json web


    【解决方案1】:

    将您的代码放入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;
    };
    &lt;div id="indexText"&gt;&lt;/div&gt;

    在这里工作 JSfiddle:https://jsfiddle.net/y2rkhp8g/1/

    【讨论】:

    • 有趣的是不需要'un-escaping',你能解释一下为什么会这样吗?
    • div 不应该也是&lt;\/div&gt; 吗? @VicJordan
    • 加一个给你答案。但这并不能解决我的问题。我编辑了我的问题。我是否正确执行了您的答案?
    • @MrYouMath 不,您没有正确实施我的答案。将所有 JavaScript 代码放入 window.onload 函数中。它会起作用的。
    • 你的意思是 window.load = function () { Everthing inside this};?试过了,但没有用。
    猜你喜欢
    • 1970-01-01
    • 2019-09-26
    • 1970-01-01
    • 2021-12-26
    • 2010-12-31
    • 2014-08-02
    • 2020-06-14
    • 2013-08-18
    • 1970-01-01
    相关资源
    最近更新 更多