如何在JavaScript中使用scriptlet [英] How to use scriptlet inside javascript
问题描述
有人可以测试此示例并共享结果吗?
http://timothypowell.net/blog/?p=23
当我这样做时:
Can someone test this example and share the results?
http://timothypowell.net/blog/?p=23
When I do:
var myVar = '<% request.getContextPath(); %>';
alert(myVar);
我得到:'<% request.getContextPath(); %>'.
从'<%request.getContextPath();中删除单引号. %>'; 给出语法错误. 如何在js函数中使用scrptlet或expresion?
Removing the enclosing single quotes from '<% request.getContextPath(); %>'; gives syntax error. How can I use the scrptlet or expresion inside a js function?
此链接的解释为我提供了帮助:
http://www.codingforums.com/showthread.php?t=172082
this link has an explanation that helped me:
http://www.codingforums.com/showthread.php?t=172082
推荐答案
这听起来像是将JSP代码放置在JavaScript页面中,或至少放置在非JSP页面中.脚本只能包含在JSP页面中(通常配置为* .jsp).
It sounds like you are placing the JSP code within a JavaScript page, or at least in a non-JSP page. Scriptlets can only be included in a JSP page (typically configured to be *.jsp).
所提供的语句如果由JSP编译器处理,将导致myVar等于",因为您正在使用<%...%>在标签之间执行Java代码,但不返回结果.
The statement as presented, if processed by the JSP compiler, would result in myVar being equal to '' as the scriptlet format you are using <% ... %> executes Java code between the tags, but does not return a result.
因此,要使用此标记,您需要手动将一个值写入请求输出流.要获得所需的功能,您需要执行以下操作:
So, to use this tag you would need to manually write a value to the request output stream. To get the desired functionality you need to do the following:
make sure your code is in a JSP page
use var myVar = '<%= request.getContextPath() %>'; (note the equals sign)
话虽如此,在大多数情况下,scriptlet被视为不良实践.在大多数情况下,您应该使用JSTL表达式和自定义标签.
With all that said, scriptlets are viewed as bad practice in most cases. For most cases, your should be using JSTL expressions and custom tags.
这篇关于如何在JavaScript中使用scriptlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!