javascript 输出 JSTL 转义了?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3260259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Output JSTL escaped?
提问by UpHelix
I am retrieving a value from our DB using JSTL. I am inserting it right into some javascript to use it as a variable. I need the output of the value the JSTL is holding to be escaped because if there are single or double quotes it breaks my script. The value is user specified.
我正在使用 JSTL 从我们的数据库中检索一个值。我将它插入到一些 javascript 中以将其用作变量。我需要转义 JSTL 持有的值的输出,因为如果有单引号或双引号,它会破坏我的脚本。该值是用户指定的。
Example:
例子:
Doing the following:
执行以下操作:
<c:set var="myVar" value="Dale's Truck"/>
<script type="text/javascript">
var mayVar = '${myVar}';
</script>
Would actually end up looking like:
实际上最终看起来像:
<script type="text/javascript">
var mayVar = 'Dale's Truck';//extra single quote breaks the JS
</script>
So I need to convert the JSTL var to be escaped like "Dale%27s Truck" before is gets to the JS because its already too late when it gets to my JS to be able to do it in JS.
因此,我需要在到达 JS 之前将 JSTL var 转换为像“Dale%27s Truck”一样进行转义,因为当它到达我的 JS 无法在 JS 中执行此操作时已经太晚了。
回答by Vivin Paliath
Try using fn:replace:
尝试使用fn:replace:
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:set var="myVar" value="Dale's Truck" />
<c:set var="search" value="'" />
<c:set var="replace" value="%27" />
<c:set var="myVar" value="${fn:replace(myVar, search, replace)}"/>
or you can escape the single quote with a backslash:
或者你可以用反斜杠转义单引号:
<c:set var="replace" value="\'" />
or if you don't even want to do all that and you are sure that the string won't contain double quotes, why not do:
或者如果您甚至不想做所有这些并且您确定该字符串不包含双引号,为什么不这样做:
var myVar = "${myVar}"; //string enclosed with double quotes instead of single quotes
But if the string has double quotes, you will still need to escape them:
但是如果字符串有双引号,你仍然需要转义它们:
<c:set var="search" value="\"" />
<c:set var="replace" value="\\"" />
回答by Anthony Chuinard
The other answer was already accepted, but David Balazic made a great point. The <spring:escapeBody>function works best.
另一个答案已被接受,但 David Balazic 提出了一个很好的观点。该<spring:escapeBody>功能效果最好。
<spring:escapeBody htmlEscape="false" javaScriptEscape="true">${myVar}</spring:escapeBody>
<spring:escapeBody htmlEscape="false" javaScriptEscape="true">${myVar}</spring:escapeBody>

