Say I have some jsp var foo

<c:set var="foo" value="foo's bar"/>

And I have the following js

<script>
 new SomeFunction('${foo}');
</script>

This will clearly produce the error

missing ) after argument list

Because the statement ends up being

new SomeFunction('foo's bar');

However, I don't want to just surround the argument ${foo} with double quotes, because foo's value could also have one double quote in its string, which would cause the same problem. Assume that foo could be any string at all. I only set it to foo's bar so the example would be clear. Currently, I'm solving the problem like so:

<script>
 new SomeFunction('<c:out value="${foo}"/>');
</script>

and within SomeFunction:

SomeFunction = new function(foo) {
  $(someSelector).text($("<div/>").html(foo).text());
}

This solution seems to work - assuming I'm not missing some corner cases. However, I'm not convinced this is the best solution. Any alternatives or suggestions for improvement? It seems sort of hacky to me to use that temporary div and I'd prefer a solution where it is not needed.

有帮助吗?

解决方案

Implement a static method using Apache commons-lang StringEscapeUtils.escapeEcmaScript() (or reimplement it yourself) to escape the special characters (single and double quotes, newlines, tabs), then make this function an EL function, and use this EL function from inside the JSP:

new SomeFunction('${myFn:escapeJs(foo)}');

See the end of this page for how to create an EL function.

其他提示

If you're using Spring, you could do this.

new SomeFunction('<spring:escapeBody javaScriptEscape="true">${foo}</spring:escapeBody>');

you can use escapeXml in c:out

 new SomeFunction('<c:out value="${foo}" escapeXml="true"/>');
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top