Printing a java scriptlet variable as if it is a JavaScript variable

浪子不回头ぞ 提交于 2019-12-02 20:06:35

问题


hello i need to output a java variable inside a javascript call inside a tag inside a jsp !

for example:

 <% String param = "hello";%>

<dmf:checkbox  name="checkbox"
  onclick = "selectAll(<%=param%>)"
/>

the javascript generated is:

selectAll(<%=param%>),this); but I actually want something like

selectAllCheckBoxes(Hello),this);

回答1:


That's not escaping. That's just printing a scriptlet variable as if it is a JavaScript variable.

Besides, your examples are confusing, they doesn't match each other and the Javascript code is syntactically invalid. I can at least tell that JavaScript string variables are to be surrounded by quotes. If you want to end up with

selectAllCheckBoxes('Hello', this);

where Hello should be obtained as a value of the scriptlet local name variable (the param is a reserved variable name, you shouldn't use it yourself), then you need to do

selectAllCheckBoxes('<%= name %>', this);

In the same way, if you want to end up with

onclick="selectAll('Hello')"

you need to do

onclick="selectAll('<%= name %>')"

That said, I strongly recommend you to stop using the old fashioned scriptlets which are been discouraged since more than a decade. JSP programmers were been recommended to use taglibs and EL only to make the JSP code more clean and robust and better maintainable. You can use taglibs such as JSTL to control the flow in the JSP page and you can use EL to access the "back-end" data. Your example can be replaced by:

<c:set var="name" value="Hello" />

...

selectAllCheckBoxes('${name}', this);



回答2:


Generate the whole attribute value with a scriptlet, like this:

<dmf:checkbox  name="checkbox"
   onclick = "<%= "selectAll(" + param + ")" %>" />



回答3:


maybe you are trying to achieve this?

var myVar = '<%= (String)request.getParameter("tab") %>'; 
loadtabs(myVar);


来源:https://stackoverflow.com/questions/1957850/printing-a-java-scriptlet-variable-as-if-it-is-a-javascript-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!