Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variable from JSP to Javascript

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?

like image 514
CIOC Avatar asked Jul 18 '13 15:07

CIOC


People also ask

How send data from JSP to JavaScript?

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.

Can we use JSP variable in 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.


1 Answers

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>
like image 97
vlio20 Avatar answered Oct 26 '22 22:10

vlio20