Java/jsp代码中的javascript [英] javascript inside java/jsp code

查看:69
本文介绍了Java/jsp代码中的javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在其中编写了javascript代码

i've written the javascript code inside

myjsp.jsp

<%
try {
    String id=request.getParameter("id");
%>
    <script type="text/javascript" >
        alert("TRY"+ <%=id %>);
        document.getElementById("mytext").readonly="readonly";
    </script>
<%
} catch (Exception e) {
%>
    <script type="text/javascript" >
        alert("CATCH"+<%=e%>);
    </script>
<%
}
%>

因此,每当将值传递到id时,它将在警报框中显示id的值,并且还将使ID为 mytext 的文本框变为禁用状态

So, whenever value will be passed into the id it'll show the value of id into the alertbox and also it'll make the textbox whose id is mytext will become disable.

因此,当我执行 myjsp.jsp 页面而不传递参数时,它将输出显示为 TRYnull ,但是当我将值传递给id,则不显示任何内容,甚至不显示警报框.任何想法!

So, when i'm executing the myjsp.jsp page without passing the parameter it shows the output as TRYnull, but when i'm passing the value into id then it's not showing anything, not even alertbox. Any idea !!

我的jsp页面

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Hello World!</h1>
       <%
try {
    String id=request.getParameter("id");
%>
    <script type="text/javascript" >
        alert("TRY"+ "<%=id %>");
        alert(document.getElementById("mytext"));
    </script>
<%
} catch (Exception e) {
%>
    <script type="text/javascript" >
        alert("CATCH"+<%=e%>);
    </script>
<%
}
%>

            <input id="mytext" name="mytext" />
    </body>
</html>

推荐答案

之所以会这样,是因为您没有传递id的请求参数时,正如您已经提到的那样,它将是null.在这种情况下,将生成以下JavaScript:

This is happening because when you pass no request parameter of id it will, as you've mentioned, be null. In this case the following JavaScript will be produced:

alert("TRY" + null);

这是有效的JavaScript,因此这就是为什么看到TRYnull的原因.

This is valid JavaScript so this is why you see TRYnull.

但是,如果您传递id请求参数,则会生成以下JavaScript:

However, if you pass in an id request parameter the following JavaScript will be generated:

alert("TRY" + foo);

尽管这在语法上是有效的JavaScript,但几乎可以肯定会产生错误(因此不会显示alert),因为在这里foo是一个很可能是undefined的变量.

Although this is syntactically valid JavaScript it is almost certain to produce an error (and therefore not show the alert) because here foo is a variable which is highly likely to be undefined.

如果您在JavaScript控制台中浏览一下,您可能会看到类似以下内容的

If you have a look in the JavaScript console you will probably see something like:

Uncaught ReferenceError: foo is not defined

您需要执行的操作将引号括在scriptlet上,以便将id的值视为String而不是变量,即

What you need to do it put quotes around your scriptlet so that the value of id is treated as a String and not a variable, i.e.

alert("TRY <%= id %>");

这篇关于Java/jsp代码中的javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆