I know there is already questions about that, but I just can´t simply get this work, I have a JSP file with a java variable in it:
String test = "Hello";
And I need to read this value in the Javascript embedded in the same JSP file, I tried so many options, but it is not working, and for security I don't want pass the value using the URL or hidden values.
Any ideas of how get this working?
simple, you can't! JSP is server side, javascript is client side meaning at the time the javascript is evaluated there is no more 'jsp code'. Save this answer.
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.
I know this one is old, but this worked for me:
var javaScriptVar="<%out.print(javaString);%>";
you need to make sure that if you are using an external js file (out of the jsp file), the above line has to be before the "include" script tag. for example this is the jsp file:
var javaScriptVar="<%out.print(javaString);%>";
<script src="some_location/test.js"></script>
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