我正在使用一个 json 对象来存储不同的内容位,其中一个可以包含 javascript 和 html 相关内容(如引号、分号、标签等),如果不进行编码,可能会破坏页面。为了解决这个问题,我正在使用:
“内容”:“<%=StringEscapeUtils.escapeHtml(StringEscapeUtils.escapeJavaScript(content))%>”
(我使用 JSP 作为服务器端技术,这是加载页面时内联生成的一些 JSON)
这可以很好地转义任何可能破坏页面的字符,但我现在需要将内容从此变量获取到文本区域。
$('textarea').val(obj.content);
我要避免的是此时发生的双重编码:
- 原文内容为:
<script>alert("hello world");</script>
- 内容变量包含:
<script>alert("hello world");</script>
- 文本区域中的文本为:
<script>alert("hello world");</script>
什么时候应该读<script>alert("hello world");</script>
有什么方法可以使这个工作?
最佳答案
$('textarea').html(obj.content);
怎么样?
在我的测试中,使用 html
函数而不是 val
为您解码 HTML 实体。
关于javascript - JSP/JavaScript/JQuery : store html/javascript content in a variable + write it to textarea,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1244554/