2

I simply need to refer to a variable from a Java class in my js file, but I am not able to do it. Here is what I have:

public class MyClass.java{
    public final static String JAVA_VARIABLE = "abc";
}

testJsp has script.js included

I need to declare the variable x, from the java file, something like below:

script.js:

function this_is_called(){
    //The below is not working
    var x = '<%=MyClass.JAVA_VARIABLE %>'; 
}

Is there some way in which I can refer to the variable declared in MyClass.java from script.js?

Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73
Saurabh J
  • 123
  • 1
  • 8

2 Answers2

2

In your test.jsp file you can assign your Java variable to a global JavaScript variable.

<script>var JAVA_VARIABLE = '<%=MyClass.JAVA_VARIABLE %>';</script>

Then access it in your script.js file

function this_is_called(){
    //The below is not working
    var x = JAVA_VARIABLE;
}

You just need to ensure the first step is before the script.js file is loaded.

Richard Dalton
  • 35,513
  • 6
  • 73
  • 91
  • Thanks @Richard Dalton, this works perfect. Actually, what I needed was to declare the class fie, something like this: var VARIABLE_CLASS ='<%=MyClass%>' And then use its global variables like this: var x =' <%=MyClass.var1%>' var y = ' <%=MyClass.var2%>' var z = ' <%=MyClass.var3%>' is this possible? – Saurabh J Nov 04 '15 at 10:24
  • @SaurabhJ No problem. If this solved your issue, feel free to click the tick next to answer to flag it as accepted. – Richard Dalton Nov 04 '15 at 10:25
0

Check this link where you can find answer to this question.

Passing java value to javascript function

Hope this must be Helpful!

Community
  • 1
  • 1
srikanth r
  • 302
  • 3
  • 20
  • Thanks srikanth, but the problem is, I need to refer to the java variable inside the .js file, whereas the above is being done in the jsp script – Saurabh J Nov 04 '15 at 10:15
  • ok than i think the solution provided by Richard Dalton is workable – srikanth r Nov 04 '15 at 10:29