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}
6
  • You might want to try this - JSP: EL expression is not evaluated. Commented Apr 20, 2014 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 Commented Apr 20, 2014 at 17:31
  • Is this in a JSP or in a JS file? Also, have you considered making an AJAX call and returning JSON? Commented Apr 20, 2014 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. Commented Apr 20, 2014 at 17:43
  • var temp = <%= x %> would not load my google map. it seems that it is not accepting value through that scripting style Commented Apr 20, 2014 at 17:48

2 Answers 2

1

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

var temp=<% x %>;
var temp=<% x %>;
var temp=${x};
Sign up to request clarification or add additional context in comments.

1 Comment

without the '=' sign it gives an error. And ${x} does not load my google map means it is not accepting that value.
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}'.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.