How can I read/access a JSP variable from JavaScript?
You can't do this directly since, as far as the JSP is concerned, it is outputting text, and as far as the page is concerned, it is just getting an HTML document. You have to generate JavaScript code to instantiate the variable, taking care to escape any characters with special meaning in JS.
JavaScript variable is on client side, JSP variables is on server side, so you can't access javascript variables in JSP.
JSP is technology based on servlet container and Java EE specification by Oracle (then Sun Microsystems). JavaScript is a scripting language. It also adds dynamic web content to the web pages but has limited features. Adds dynamic functional aspect to the static web pages with a rich user experience.
alert("${variable}");
or
alert("<%=var%>");
or full example
<html> <head> <script language="javascript"> function access(){ <% String str="Hello World"; %> var s="<%=str%>"; alert(s); } </script> </head> <body onload="access()"> </body> </html>
Note: sanitize the input before rendering it, it may open whole lot of XSS possibilities
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