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
JavaScript variable is on client side, JSP variables is on server side, so you can't access javascript variables in JSP. But you can store needed data in hidden fields, set its value in client and get it on server over GET or POST.
Yes, We can use javaScript with JSP page. As we know that javaScript is a Client-side script and JSP is a Server-side so we can attach a form validation to a JSP page to redirect HTML page and javaScript content. -Before submitting page to web server, it should be validate HTML field data.
Using DWR framework, you can send javascript variables to java.
The easiest way to see the difference is one simple sentence: JSP is the server-side scripting language i.e. it runs on the server while JavaScript runs on the client. As a result, JSP is more used to change the content of a webpage, and JavaScript for the presentation. It is quite common to use both on the same page.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With