JavaScript转义表单值 [英] JavaScript Escaping Form Values
问题描述
我有一个textarea元素动态显示在一个JSP上。在无效表单提交的情况下,我需要使用用户输入的值重新填充这些字段。我这样做(注意:简化版本):
var textareaBox = document.getElementById(myTextArea);
if(textareaBox){
textareaBox.value ='$ {myForm.myValue}';
}
一切正常,直到用户在包含特殊字符的框中输入值。我已经尝试单独使用转义
和 unescape
JavaScript函数,并结合无效。
使用 JSTL 的< c:out>
标签以转义它,并将其分配为文本区域的 innerHTML
:
textareaBox.innerHTML ='< c:out value =$ {myForm.myValue}/>';
但是,为什么不直接在textarea的正文中显示它,而不需要JS? p>
< textarea id =myTextArea>< c:out value =$ {myForm.myValue}/> < / textarea的>
< c:out>
并且其EL函数对应 fn:escapeXml()
)转义XML特殊字符。
另请参见:
I know there are a lot of JavaScript escaping questions, but nothing seemed to fit my needs.
I have textarea elements being dynamically displayed on a JSP. In the case of invalid form submits, I need to repopulate these fields with the values the user entered. I am doing this like so (note: simplified version):
var textareaBox = document.getElementById("myTextArea");
if (textareaBox) {
textareaBox.value = '${myForm.myValue}';
}
Everything works fine until the user enters a value in the box that contains special characters. I've tried using the escape
and unescape
JavaScript functions individually and combined to no avail.
Does anyone know how I can handle these special character values? Note that I obviously do not want the escaped text in the textarea as this would not look good to users.
Use JSTL's <c:out>
tag to escape it and assign it as innerHTML
of the text area:
textareaBox.innerHTML = '<c:out value="${myForm.myValue}" />';
But why don't you just display it in textarea's body directly without the need for JS?
<textarea id="myTextArea"><c:out value="${myForm.myValue}" /></textarea>
The <c:out>
(and its EL function counterpart fn:escapeXml()
) escapes XML special characters.
See also:
这篇关于JavaScript转义表单值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!