在jsp中通过Java访问javascript

accessing javascript through java in jsp

本文关键字:Java 访问 javascript jsp      更新时间:2023-09-26

我的代码现在看起来是这样的

<%
    if (request != null) {
        bustOut;
    }
%>
<script language="javascript">
function bustOut(){
   var newWin = window.open("the real url", "subWindow","height=500,width=700,resizable=yes,scrollbars=yes"); 
}
</script>

如何在Java代码中调用javascript函数?或者这是不可能的?

JSP在webserver上运行,根据web浏览器的请求生成/生成HTML/CSS/JS代码。Webserver发送HTML/CSS/JS给浏览器。web浏览器运行HTML/CSS/JS。因此,您只需要让JSP将其打印为JS代码即可。

<script language="javascript">
    function bustOut(){
       var newWin = window.open("the real url", "subWindow","height=500,width=700,resizable=yes,scrollbars=yes"); 
    }
    <% 
        if (foo != null) { 
            out.print("bustOut();");
        }
    %>
</script>

或者使用EL

更好
<script language="javascript">
    function bustOut(){
       var newWin = window.open("the real url", "subWindow","height=500,width=700,resizable=yes,scrollbars=yes"); 
    }
    ${not empty foo ? 'bustOut();' : ''}
</script>

(注意,我将属性名称更改为foo,因为request代表HttpServletRequest,这可能会使其他人感到困惑,因为这从来不是null)

无论哪种方式,当条件为真时,生成的HTML(您应该在浏览器中打开页面,右键单击并选择查看源)应该如下所示:
<script language="javascript">
    function bustOut(){
       var newWin = window.open("the real url", "subWindow","height=500,width=700,resizable=yes,scrollbars=yes"); 
    }
    bustOut();
</script>

它现在会打开你头上的灯泡吗?

不能从java调用javascript函数

java代码在服务器端执行,javascript -在客户端执行。

你似乎需要的是有条件地打开一个新窗口的文档加载。:

<c:if test="${shouldDisplayWindow}">
     $(document).ready(function() {
         bustOut();
     });
</c:if>

(这是上面用于检测文档加载的jQuery。您可以将其替换为纯javascript (window.onload = function() {..}document.onload = function() {..}我认为)

注意request != null是没有意义的条件——请求在JSP中永远不会是null

最后-使用jstl标签(如我所示)而不是java代码(scriptlet)。