0

I want to use a Javascript variable in JSP scriplet of the same page. See example below.

<script language="javascript">
var i=10;
</script >

< % out.println(i); % >

It should print the value of i defined in script tag above. Both script and scriplet are part of the same .jsp page

Chuck
  • 998
  • 8
  • 17
  • 30
Manjunath
  • 1
  • 1
  • 2
  • possible duplicate of [passing javascript variable value to JSP variable](http://stackoverflow.com/questions/5386984/passing-javascript-variable-value-to-jsp-variable). See also [this answer](http://stackoverflow.com/a/7016795/502381). – JJJ Mar 11 '12 at 09:06
  • 2
    You're confused. JSP is compiled on the server and sent to the client as pure HTML/JS. Then, once the browser gets the page, it executes the JS. JSP is executed on the server. JS is executed on the client. There is no way to "share variables." – Tony R Mar 11 '12 at 09:27
  • is there any way of passing variable from JS to jsp...i have got the variable in JS using src attribute of script tag and want to use it outside JS – Manjunath Mar 11 '12 at 11:14
  • The line `var i=10;` is not code for the JSP. It is just another line of HTML for it. And even if your next statement is `i=i+10;` that code will not get executed in the server(or in the JSP). Instead, it would be sent as is to the browser and executed there. – Sundeep Mar 11 '12 at 11:54
  • possible duplicate of [passing value to JSP via javaScript](http://stackoverflow.com/questions/4021474/passing-value-to-jsp-via-javascript) – Shadow The GPT Wizard Mar 11 '12 at 12:37

1 Answers1

0
<div id='out'>
<div>

<script language="javascript">
var i=10;
document.getElementById('out').innerHTML = i ;
</script >

It is not really an answer , because your problem is irrelevant. There is a difference between what gets executed serverside and clientside , and your javascript will get executed clientside , the jsp tags on the server , etc... Either you define and display i in java , or in javascript.

mpm
  • 20,148
  • 7
  • 50
  • 55