在同一个jsp上从javascript访问java变量

时间:2022-09-25 12:19:54

Is it possible to access a String type variable defined in jsp from a javascript on the same page?

是否可以从相同页面上的javascript访问jsp中定义的字符串类型变量?

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1255">
<title>Insert title here</title>
<script type="text/javascript">  
foo();
function foo()  
{  
var value = "<%=myVar%>";  
alert(value);   
}  
</script>  
</head>
<body>

<%

String myVar="blabla";
%>

</body>

</html>

In eclipse I am getting an error

在eclipse中,我将得到一个错误

myVar cannot be resolved to a variable

1 个解决方案

#1


21  

This won't work since you're trying to use an undefined variable. The code is generated like this:

这将不起作用,因为您正在尝试使用一个未定义的变量。代码是这样生成的:

... = myVar;
//...
String myVar = "blabla";

Doesn't make sense, right? So, in order to make this work you should declare the variable before using it (as always):

没有意义的,对吧?因此,为了使这一工作,您应该在使用变量之前声明它(一如既往):

<%
    String myVar="blabla";
%>
<script type="text/javascript">
    foo();
    function foo() {
        var value = "<%=myVar%>";
        alert(value);
    }
</script>

Still, usage of scriptlets is extremely discouraged. Assuming you're using JSTL and Expression Language (EL), this can be rewritten to:

尽管如此,使用scriptlet仍然是非常不鼓励的。假设您正在使用JSTL和Expression Language (EL),这可以重写为:

<c:set name="myVar" value="blabla" />
<script type="text/javascript">  
    foo();
    function foo() {
        var value = "${myVar}";
        alert(value);
    }
</script>

If your variable has characters like " inside, then this approach will faile. You can escape the result by using <c:out> from JSTL:

如果您的变量具有“内部”这样的字符,那么这种方法将失败。您可以使用JSTL的 来转义结果:

var value = "<c:out value='${myVar}' />";

More info:

更多信息:

#1


21  

This won't work since you're trying to use an undefined variable. The code is generated like this:

这将不起作用,因为您正在尝试使用一个未定义的变量。代码是这样生成的:

... = myVar;
//...
String myVar = "blabla";

Doesn't make sense, right? So, in order to make this work you should declare the variable before using it (as always):

没有意义的,对吧?因此,为了使这一工作,您应该在使用变量之前声明它(一如既往):

<%
    String myVar="blabla";
%>
<script type="text/javascript">
    foo();
    function foo() {
        var value = "<%=myVar%>";
        alert(value);
    }
</script>

Still, usage of scriptlets is extremely discouraged. Assuming you're using JSTL and Expression Language (EL), this can be rewritten to:

尽管如此,使用scriptlet仍然是非常不鼓励的。假设您正在使用JSTL和Expression Language (EL),这可以重写为:

<c:set name="myVar" value="blabla" />
<script type="text/javascript">  
    foo();
    function foo() {
        var value = "${myVar}";
        alert(value);
    }
</script>

If your variable has characters like " inside, then this approach will faile. You can escape the result by using <c:out> from JSTL:

如果您的变量具有“内部”这样的字符,那么这种方法将失败。您可以使用JSTL的 来转义结果:

var value = "<c:out value='${myVar}' />";

More info:

更多信息: