How to pass Special characters to JavaScript in JSP..?
i know that there is an function Escape() in javascript, escapeXml in JSTL, i used several ways for solving this thing but didnt get the solution. The problem is ..
the JSTL variable suppose say ${str} has value "system # with ^%$ / <".
i pass this value to javascript as OnClick="special('${str}')"
i get an error as:-
Er开发者_开发知识库ror: unterminated string literal
Source File: http://localhost:8080/..
Line: 1, Column: 27
Source Code:
special('system # with ^%$ / <
I am not able to pass the string is itself to javaScript.
PS : i copied the above error statement from mozilla error console.
It sounds like you need to escape the double and single quotes in the string. I'd do this with a function you define, rather than fn:replace()
because the quoting is kind of gnarly.
The simplest way to do this is to use the Apache StringEscapeUtils#escapeJavaScript()
function.
Escapes the characters in a
String
using JavaScript String rules.Escapes any values it finds into their JavaScript String form. Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)
So a tab becomes the characters
'\\'
and't'
.The only difference between Java strings and JavaScript strings is that in JavaScript, a >single quote must be escaped.
Example:
input string: He didn't say, "Stop!" output string: He didn\'t say, \"Stop!\"
So your servlet could do this:
request.setAttribute("str",
StringEscapeUtils.escapeJavaScript("\"system # with ^%$ / <\""));
Then your JSP can simply contain:
... onclick="'${str}'" ...
You could create a custom EL function to do this as well (using the same escapeJavaScript()
function underneath) but that is more complicated.
精彩评论