Vge Shi
Vge Shi

Reputation: 213

Accessing java variable from javascript on same jsp

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

<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

myVar cannot be resolved to a variable

Upvotes: 13

Views: 108000

Answers (1)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85809

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:

<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:

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

More info:

Upvotes: 27

Related Questions