简体   繁体   English

如何处理jsp页面中javascript中的单行引用?

[英]How to deal with sigle quote in javascript in jsp page?

onclick= "_deleteWPSchemeData(${viewWPMasterGrid.id}, '${viewWPMasterGrid.name}')"

${viewWPMasterGrid.name} retutrns me a string(for eg WPWINT OFF ALL'10) which often has single quote character so from the calling javascript method I am not getting the second parameter at all. $ {viewWPMasterGrid.name}退给我一个字符串(例如WPWINT OFF ALL'10),该字符串通常具有单引号字符,因此从调用javascript方法中我根本没有得到第二个参数。 How to deal with problem? 如何处理问题?

When a dynamic String can be put inside a JavaScript string literal, it should be JS-escaped. 当可以将动态字符串放入JavaScript字符串文字中时,应将其转义为JS。 Just as when a dynamic String is put inside a HTML page, it's HTML-escaped. 就像将动态String放在HTML页面中一样,它也是HTML转义的。

Use commons-lang StringEscapeUtils.escapeECMAScript (or escapeJavaScript depending on the version) to escape the String. 使用commons-lang StringEscapeUtils.escapeECMAScript (或escapeJavaScript取决于版本)来转义字符串。 You could create a very simple EL function to do that straight from the JSP. 您可以创建一个非常简单的EL函数来直接从JSP进行此操作。

Note that you could have problems with single quotes, but also double quotes, tags, EOLs, backslash, which must all be escaped in a JS String literal. 请注意,单引号,双引号,标签,EOL,反斜杠都可能存在问题,这些问题必须全部用JS String文字转义。

It looks like you could split the second parameter out into its own variable first. 看来您可以先将第二个参数拆分为自己的变量。 If I have understood your question correctly. 如果我正确理解了您的问题。

var viewWPMasterGridName = "${viewWPMasterGrid.name}";
onclick = "_deleteWPSchemeData(${viewWPMasterGrid.id},'" + viewWPMasterGridName + "')";

使用'${viewWPMasterGrid.name.replaceAll("'", "\\'")}'

尝试这个,

var name = "${viewWPMasterGrid.name}".replace(/'/g,"\\'");

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

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