我需要form:hidden到输出值属性用单引号括起来

时间:2014-03-20 10:47:23

标签: javascript html json spring spring-form

我正在使用form:spring表单中的隐藏标记来存储json中的一些值

<form:hidden path="myJson"/>

这个JSON值具有这种性质:

[{"html":"<a href=\"index.html\">text has &#39;single quotes&#39; or even \"double quotes\"</a>"}]

因此JSON具有双引号,如果它们在字符串中,则使用\来进行转义,并且可能具有作为其HTML实体进行转义的单引号

&#39;

所以我一直在使用像这样的普通输入类型=“隐藏”:

<input type="hidden" name="myJson" value='[{"html":"<a href=\"index.html\">text has &#39;single quotes&#39; or even \"double quotes\"</a>"}]'>

通知值属性使用单引号。现在,使用spring表单输出使用双引号:

<input type="hidden" name="myJson" value="[{"html":"<a href=\"index.html\">text has &#39;single quotes&#39; or even \"double quotes\"</a>"}]">

所以,当我得到这个值时,我只得到“[{”,其余部分写在页面正文中。

另外,如果我不能像这样使用htmlEscape =“false”:

<input:hidden path="myJson" htmlEscape="false"/>

因为我得到的所有值都充满了htmlEntities:

[{&quot;html;&quot...

然后,使用此JSON值的库按字面读取它们,而不是写入链接,而是在正文中写入完整的HTML。

有没有办法改变输入的输出:隐藏所以它显示单引号而不是双引号?

或者,是否有更好的方法来实现这一目标?要求是这个JSON可以包含HTML以及单引号和双引号。

谢谢!

1 个答案:

答案 0 :(得分:2)

您可以尝试使用javascript,如下所示:

HTML

<input type="hidden" id="example" value="">

JS

var json = JSON.stringify([{"product_id":123,"name":"stack"}]);
document.getElementById('example').setAttribute('value', json.replace(/"/g, "&quot;"));