0

这是用 a.jsp 编写的代码:

    <script type="text/javascript" >
    function chk(d,e)
    {
     var x = d.split('/')
     var y = e.split('/')
     var a = new Date(x[2],x[0],x[1])
     var b = new Date(y[2],y[0],y[1])
     var c = ( b - a )
     var p= c / (1000 * 60 * 60 * 24);
    }
    </script>

    <% String b="2013/07/12";
       String c="2013/07/14";%>

   <script>
    var myVar=chk('$b','$c');
   </script>

   <body>
   <% String st="<script>document.writeln(myVar)</script>";
       out.println("value="+st); %>
   </body>

我想得到这两个日期(即'b'和'c')之间的天数(即'p')作为输出。但我得到的输出是“value=NaN”。这段代码有什么问题?请帮忙。

4

3 回答 3

1

This question was tricky to answer. First, looks like you want to pass the variables declared in scriptlet to your JavaScript using EL. To accomplish this, you should:

  • Set the variable in scriptlet as pageContext attribute or request attribute as explained here: How to evaluate a scriptlet variable in EL?
  • Use JSTL <c:out> to send the variable from EL to your JavaScript function.
  • Following GauravSharma's answer suggestion, add a return p; at the end of your JavaScript function.

Your code should look like this (at least works for me using Tomcat 7 and prints 2 in the navigator):

<script type="text/javascript">
    function chk(d, e) {
        var x = d.split('/');
        var y = e.split('/');
        var a = new Date(x[0], x[1] - 1, x[2]);
        var b = new Date(y[0], y[1] - 1, y[2]);
        var c = (b - a);
        var p = c / (1000 * 60 * 60 * 24);
        return p;
    }
</script>
<%
    String b = "2013/07/12";
    String c = "2013/07/14";
    pageContext.setAttribute("b", b);
    pageContext.setAttribute("c", c);
%>

<script>
    var myVar = chk('<c:out value="${b}" />', '<c:out value="${c}" />');
</script>

<body>
    <%
        String st = "<script>document.writeln(myVar)</script>";
        out.println("value=" + st);
    %>
</body>

As said in my comment on your question, this looks like an exercise for practicing about scriptlets, EL, JSTL and JavaScript integration. This kind of code is not meant to be used in a live production system NEVER. Scriptlets usage is discouraged since long time. Refer to: How to avoid Java code in JSP files?. Also, show this to your teacher, professor or whoever is teaching you about Java web development.

于 2013-07-12T17:49:28.457 回答
0

在函数的最后,添加return p;.
您的函数没有返回任何内容,这就是undefined在屏幕上写入的原因。

function chk(d,e)
{

 var x = d.split('/')
 var y = e.split('/')
 var a = new Date(x[2],x[0],x[1])
 var b = new Date(y[2],y[0],y[1])
 var c = ( b - a )
 var p= c / (1000 * 60 * 60 * 24);
 return p;
}
于 2013-07-12T17:21:48.680 回答
-1

只需调用写这个

var myVar=chk('$b','$c');

准备好文件。

因为JSP刚刚写到script.Notdocument还没有执行。

于 2013-07-12T15:57:35.107 回答