简体   繁体   English

是否可以从jsp的java部分执行javascript函数?

[英]Is it possible to execute a javascript function from the java part of jsp?

In jsp , I want a function defined in javascript在 jsp 中,我想要一个在 javascript 中定义的函数

<script type="text/javascript">
function forSignup(){

    if(document.getElementById("sign").style.display=='none')
    {

        document.getElementById("sign").style.display='block';
        document.getElementById("login form").style.display='none';
    }

    else
    {
        document.getElementById("login form").style.display='block';
        document.getElementById("sign").style.display='none';
    }
</script> 

to be executed when called from the java part of jsp <% %> on a condition when a servlet sends a value of an integer as 1 .在 servlet 发送整数值作为 1 的条件下从 jsp <% %>的 java 部分调用时执行。

Is it possible to do ?有可能吗?

if yes please tell me how should I perform it ?如果是,请告诉我应该如何执行?

I assume this is roughly what you're looking for.我假设这大致是你正在寻找的。 If a server side variable (intValue) is equal to 1, then call the function, otherwise do not.如果服务器端变量 (intValue) 等于 1,则调用该函数,否则不调用。

<% if (intValue == 1) { %>
    <script type="text/javascript">
        forSignup();
    </script>
<% } %>

Bear in mind though, that you're not actually calling this Javascript function "from Java".但请记住,您实际上并不是在“从 Java”调用这个 Javascript 函数。 You are merely ensuring that the Javascript function is called based on the server side condition, dependent on the integer value in question.您只是确保根据服务器端条件调用 Javascript 函数,具体取决于所讨论的整数值。

您可以使用<c:if>块基于 JSP 中的变量包含 JavaScript。

JavaScript can be executed from Java code, but it isn't simple, and the code you posted has to run from the DOM and thus can't be handled server-side. JavaScript 可以从 Java 代码执行,但它并不简单,您发布的代码必须从 DOM 运行,因此无法在服务器端处理。 Moreover, using scriptlets is strongly discouraged;此外,强烈建议不要使用 scriptlet; it's much better to prepare the model for a page (usually using a framework such as Spring MVC) and then use templates for rendering only.最好为页面准备模型(通常使用 Spring MVC 等框架),然后仅使用模板进行渲染。

What you're wanting to do is conditional logic, determining whether elements are displayed based on some state such as whether the user is logged in. Use <c:if> to selectively include code in the rendered HTML (and just set CSS directly instead of taking a detour through JavaScript).您想要做的是条件逻辑,根据某些状态(例如用户是否登录)来确定元素是否显示。使用<c:if>有选择地将代码包含在呈现的 HTML 中(只需直接设置 CSS通过JavaScript绕道而行)。

if you want to execute java code in javascript method如果你想在javascript方法中执行java代码

<script >
 function login(){
 <% System.out.println("Hiiiiiiiii"); 

 %>
 var password="test"
 }
</script>

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

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