This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Assign Jsp variable to Javascript variable

 
Muthiah Raja
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to assign JSP String variable to Javascript variable.
For that i use the follwing code

<% String str="Raja"; %>
var s=<%=str%>;
alert(s);

But this code is not worked.

Kindly help me.
 
Bosun Bello
Ranch Hand
Posts: 1510
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You did not declare the variable correctly. try this:

<%! String str="Raja"; %>
 
Vijesh Nair
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mr Bosun was asked to create a global variable in your jsp , but thats not a good practise.Why because while the jsp got converted to translated to servlet the global declarations will reside outside of service() method ,hence thats not thread safe.So for you the best practise is try to store the value of that variable in an hidden html element , then using the simple javascript norms you will be able to get the value of the variable.The JSP implicit objects can directly accessed in your javascript code.

Thanks Vichu.
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Muthiah,
What you are doing is fine.
You just forgot to add the quotes to the Javascript literal.

var s = "<%=str%>";

Remember, you're not actually passing the value from the JSP realm to the Javascript realm. The output of your JSP's execution is Javascript code.
The best way to get your head around this is to view the HTML source from your browser often.

In the source you would have seen:
var s=Raja;

Instead of:
var s = "Raja";


And Vijesh is correct.
Declaring the string as an instance variable not only wouldn't have helped in this case, it most likely would have lead to threading problems in the application.
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Muthiah Raja:
I am trying to assign JSP String variable to Javascript variable.
For that i use the follwing code

<% String str="Raja"; %>
var s=<%=str%>;
alert(s);

But this code is not worked.

Instead of writting var s=<%=str%>;

I try var s='<%=str%>';
I try var s="<%=str%>";

this code also not worked.

Kindly help me.


It works for me:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic