json jquery - 将html显示为文本而不是html

时间:2011-10-19 08:26:32

标签: jquery html json

我正在使用jQuery调用一个php页面(通过ajax)进入我的服务器以获取一些数据。然后将数据编码为json并返回到页面。然后我用jQuery解析json。我在显示返回的html项时遇到问题。在json对象中,所讨论的数据是“描述”键的值。 json返回如下:

{ "description" : "Check the Wiki article to see what states require Two-Party Notification. (<a href="http://intranet.clickmotive.com/Wiki/Call%20Recording%20-%20Two%20Party%20Notification%20States.ashx" target="_blank">wiki link</a>)" }

然后我使用一个简单的函数,我在这里解码html。然后我正在使用的函数是这个(我将上面的键的值传递给这个函数):

function htmlDecode(value){
    return $('<div/>').html(value).text();
}

将文本解码如下:

Check the Wiki article to see what states require Two-Party Notification. (<a href="http://intranet.clickmotive.com/Wiki/Call%20Recording%20-%20Two%20Party%20Notification%20States.ashx" target="_blank">wiki link</a>)

这是我将它添加到页面的方式:(其中'description'变量是从json数据设置的)

$("#description").append(htmlDecode(description));

我的问题是它将完整的html显示为文本而不是html。因此,没有创建链接。这段代码有什么问题?我肯定错过了什么。如果您有任何疑问,请告诉我!谢谢!

3 个答案:

答案 0 :(得分:2)

您的数据是双htmlentities()编码的。所以有两种方法可以解决这个问题:

的jQuery

你所做的事情几乎是好的:

function htmlDecode(value){
    return $('<div/>').html($('<div/>').html(value).text()).text();
}

或者简单地将htmlDecode()方法称为@Dennis两次。

htmlDecode(htmlDecode(description));

JsonML

我认为最好使用JsonML代替简单的JSON。

JsonML是XML文档(或节点)的JSON编码,因此实际上它更适合您的问题。

我写了一个JsonML jQuery插件,你可以从github获取它。你也需要一个PHP JsonML编码器,它易于编写,我认为应该也有可用的实现。

答案 1 :(得分:1)

您的源json数据已编码两次,因此您的所有&符号都会被转义。

将来电替换为:

htmlDecode(htmlDecode(description))

它会起作用。

答案 2 :(得分:1)

如果您使用的是Jquery模板,那么在模板中您只需添加{{html expression}}

http://api.jquery.com/template-tag-html/

由于

相关问题