简体   繁体   English

JSP将带有XML字符的String属性传递给JavaScript函数不起作用

[英]JSP passing String attribute with XML characters to JavaScript function not working

I need to pass a jsp string variable to a javascript function. 我需要将jsp字符串变量传递给javascript函数。 This is usually fairly simple but I'm currently having issues because the string I'm passing contains xml characters. 这通常很简单,但是我目前遇到了问题,因为我传递的字符串包含xml字符。

This is the jsp (shortened for clarity purpose) 这是jsp(为清楚起见而缩写)

<%@page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core"   prefix="c"%>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <body>
        <input type="button" value="MyButton" onclick="myFunction('<c:out value="${current.xmlOutput}"/>');" />  
    </body>
 </html>  

The value in "current.xmlOutput" contains the following “ current.xmlOutput”中的值包含以下内容

<chart caption='Flight Hours' xAxisName='Flight' yAxisName='Hours' ><set label='AC908' value='126' /><set label='AC812' value='234' /><set label='AC184' value='78' /></chart>

The generated JSP source 生成的JSP源

<input type="button" value="MyButton" onclick="myFunction('&lt; chart  caption  = &#039;Flight Hours&#039; xAxisName  = &#039;Flight&#039; yAxisName  = &#039;Hours&#039;&gt;&lt; label  = &#039;AC908&#039; value  = &#039;126&#039; /&gt; &lt; label  = &#039;AC812&#039; value  = &#039;234&#039; /&gt; &lt; label  = &#039;AC184&#039; value  = &#039;78&#039; /&gt; &lt;/ chart &gt;');" />

When I press the button it never calls the function. 当我按下按钮时,它永远不会调用该函数。 If "current.xmlOutput" contains a simple String like "Test" everything works fine. 如果“ current.xmlOutput”包含一个简单的字符串(如“ Test”),则一切正常。 In the chrome developer tools it give me the following message "Uncaught SyntaxError: Unexpected identifier " 在chrome开发人员工具中,它给我以下消息“ Uncaught SyntaxError:Unexpected identifier”

Also, I have a filter that does this req.setCharacterEncoding("UTF-8"); 另外,我有一个过滤器可以执行此操作req.setCharacterEncoding(“ UTF-8”); Any one know what I'm doing wrong? 有人知道我在做什么错吗? Any help would be appreciated. 任何帮助,将不胜感激。

Thanks 谢谢

Turns out my issue was with the single quotes inside the xml. 原来我的问题是xml中的单引号。 Instead of 代替

<chart caption='Flight Hours' 

it should have been 应该是

<chart caption=\'Flight Hours\'

If you're passing the string via Java/Servlet to a jsp, then you'll need this 如果要通过Java / Servlet将字符串传递给jsp,则需要此

String xmlToPass = "<chart caption = \\'Flight Hours\\' "

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

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