How can I access an JavaScript variable from within an JSP page ?
A:
Not possible. You can access a JSP variable in javascript but the javascript variable can not be accessed in JSP.
RaviG
2010-05-22 18:14:36
You can't *"access a JSP variable in [client-side] javascript"*. You can send the variable's *value* to the client by outputting it within the Javascript code in a server-generated `script` block, which isn't the same thing.
T.J. Crowder
2010-05-22 18:21:09
Can you explain if it is possible to do it other way round ?
Rachel
2010-05-22 18:21:10
Can you provide an example of how can I access and client side variable's value on the server side ?
Rachel
2010-05-22 18:22:31
@Rachel: you would need either JavaScript make a request to the server (AJAX) or populate a form with the values and submit that.
Dormilich
2010-05-22 18:38:23
@T.J.Crowder: Thank you for the example, now am able to understand this concept more clearly.
Rachel
2010-05-22 21:48:16
I down voted your answer, because it seems you are answering a perfectly valid question that was not asked.
2010-05-23 05:30:38
@austin: I guess you kind of missed the minor detail that the **OP** felt I'd answered her question. You know, what with her comments, and that big green checkmark. Downvoting is pretty darned silly given that evidence.
T.J. Crowder
2010-05-23 06:04:38
+1
A:
You can't access it directly. That's because this is how a page is rendered:
1. On the server, the JSP code runs and generates HTML/JavaScript.
2. The HTML/JavaScript is sent to the client's browser.
3. The browser then renders the HTML and runs the JavaScript.
As you can see, the JavaScript is run way after the JSP runs, so they can't directly access each other's variables.
What you could do is output JavaScript code which initializes a variable based on a value in the JSP code. For example, if you generate code like this (excuse my syntax, I don't know JSP):
<script>
var JSPValue = /*jsp code that prints the value of a variable*/;
//rest of JavaScript code...
</script>
Then the JavaScript can accss JSPValue
, just because it will have been put there by the server. For example, when sent to the browser, it might look like:
<script>
var JSPValue = 42;
//rest of JavaScript code...
</script>
Claudiu
2010-05-22 18:27:56
You suggestion of creating a global JavaScript variable does answer the question, but is not a recommended best practice. Dynamic creation of arbitrary global variables from JSP tends to lead developers who do not write for JavaScript primarily into a false sense of functionality that is prone to namespace collisions and unexpected code failure.
2010-05-23 05:34:14