0

How to assign a java variable vale to an javascript varible. I have tried the following scripting elements:

<%
double x=23.35;
%>
var temp='<%= x %>';
var temp="<%= x %>";
var temp='${x}';

they returned an output as follows:

<%= x %>
<%= x %>
${x}
infused
  • 24,000
  • 13
  • 68
  • 78
  • You might want to try this - [JSP: EL expression is not evaluated](http://stackoverflow.com/q/793983/738746). – Bhesh Gurung Apr 20 '14 at 17:19
  • I tried your suggestion Bhesh but no change in my output. Actually I am not working on an web application, but calling this jsp file from a java code. I am working on SWT browser for uploading google maps – Shashank Bhagat Apr 20 '14 at 17:31
  • Is this in a JSP or in a JS file? Also, have you considered making an AJAX call and returning JSON? – Elliott Frisch Apr 20 '14 at 17:32
  • It's probably because your java call is in quotations. Try `var temp = <%= x %>`. If this is a JSP file, the value should be replaced before the JavaScript interpreter gets to it. – rescuecreative Apr 20 '14 at 17:43
  • var temp = <%= x %> would not load my google map. it seems that it is not accepting value through that scripting style – Shashank Bhagat Apr 20 '14 at 17:48
  • @ShashankBhagat: 'I am working on SWT browser' - does this mean your application is a desktop application, rather than a web application? In that case, why are you using JSPs? – Luke Woodward Apr 20 '14 at 19:19

2 Answers2

1

Try this-it should work. (No '=' needed inside java code).

var temp=<% x %>;
var temp=<% x %>;
var temp=${x};
kellzer
  • 131
  • 1
  • 3
  • 18
0

You have tried three ways. I have tried in JSP inside the script tag and below work for me fine except for the third way.

 <% double x = 23.35; %>
    
 var temp = <%=x%>;
 console.log(temp);
 console.log(typeof(temp));

 var temp2 = '<%=x%>';
 console.log(temp2);
 console.log(typeof(temp2));

 var temp3 = "<%=x%>";
 console.log(temp3);
 console.log(typeof(temp3));

The difference is if we assign value to a variable within single quotes or double quotes, it treated as a string otherwise number. If you assign value as <c:set name="x" value="23.35" /> then can access by '${x}'.