JavaScript Escaping Form Values

佐手、 提交于 2019-12-13 06:50:21

问题


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.


回答1:


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:

  • Not able to display special characters properly in a JSP page


来源:https://stackoverflow.com/questions/8346198/javascript-escaping-form-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!