简体   繁体   English

需要从 js 文件中引用 Java 全局变量

[英]Need to refer to Java global variable from js file

I simply need to refer to a variable from a Java class in my js file, but I am not able to do it.我只需要从我的 js 文件中的 Java 类中引用一个变量,但我无法做到。 Here is what I have:这是我所拥有的:

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

testJsp has script.js included testJsp包含script.js

I need to declare the variable x, from the java file, something like below:我需要从 java 文件中声明变量 x,如下所示:

script.js : 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 ?有什么方法可以让我从script.js引用MyClass.java声明的变量?

In your test.jsp file you can assign your Java variable to a global JavaScript variable.在 test.jsp 文件中,您可以将 Java 变量分配给全局 JavaScript 变量。

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

Then access it in your script.js file然后在你的 script.js 文件中访问它

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.您只需要确保第一步是在加载 script.js 文件之前。

Check this link where you can find answer to this question.检查此链接,您可以在其中找到此问题的答案。

Passing java value to javascript function 将java值传递给javascript函数

Hope this must be Helpful!希望这一定有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM