简体   繁体   English

单引号JSP到JavaScript函数

[英]Single quote JSP to JavaScript function

I have a string that must be used to be passed into a JavaScript function. 我有一个必须用于传递给JavaScript函数的字符串。 I have tried many ways, but I still cannot make it to work. 我尝试了很多方法,但我仍然无法使其发挥作用。

<a href="javascript:goFac('<%=name%>')"><%=name%></a>

The name field is a string that contains single quotes such as It's Morning . name字段是一个包含单引号的字符串,例如It's Morning I have tried to use: 我试过用:

String nameString = rs.getString("name");
nameString = nameString.replaceAll("'","\'");

<a href="javascript:goFac('<%=nameString %>')"><%=nameString%></a>

And also 并且

nameString = URLEncoder.encode(nameString);

And also 并且

nameString = nameString.replaceAll("'","&#39;");

And also 并且

 nameString = nameString.replaceAll("'","&apos;");

I still cannot get it to work. 我仍然无法让它发挥作用。 And also I can't go for EL. 我也不能选择EL。

If you want to replace a single quote (') in a String with a JavaScript-escaped (backslashed) single quote (\\') in Java code then you need to escape the backslash character (with a backslash!). 如果要在Java代码中使用JavaScript转义(反斜杠)单引号(\\')替换String中的单引号('),则需要转义反斜杠字符(使用反斜杠!)。 For example: 例如:

nameString = nameString.replaceAll("'","\\'"); 

See also: String.replaceAll single backslashes with double backslashes 另请参见: String.replaceAll带有双反斜杠的单反斜杠

尝试使用String.fromCharCode(39)而不是单引号,String.fromCharCode(39)是单引号的ASCII代码。

The following worked for me, as the HTML encoding is done before the function call and replaced the single quote with &#39; 以下对我有用,因为HTML编码在函数调用之前完成,并用&#39;替换单引号&#39; .

nameString = nameString.replaceAll("&#39;","\\'");

If you are doing it inside JSP tag, you need to have sufficient backslashes for one of them to actually make it into the web page. 如果您在JSP标记内执行此操作,则需要有足够的反斜杠才能将其实际放入网页中。 The code would be: 代码是:

<a href="javascript:goFac('<%=nameString.replaceAll("'", "\\\\'") %>')"><%=nameString%></a>

You need one backslash to escape the other backslash and each of those needs to be escaped - hence four backslashes (yuck). 你需要一个反斜杠来逃避另一个反斜杠,并且每个都需要被转义 - 因此有四个反斜杠(yuck)。

Hope that helps. 希望有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM