[英]Calling JavaScript function in a .js file from Java
What is the best way to call a JavaScript function in a different .js file from a Java file? 在不同于Java文件的.js文件中调用JavaScript函数的最佳方法是什么?
Say, I have a String like so in a Java file: 说,我在Java文件中有一个像这样的字符串:
String test = "[name1, name2, name2]";
What I am trying to do is the following: 我正在尝试做以下事情:
Thanks, Sony 谢谢,索尼
If you want to integrate Javascript and Java, then you can use Rhino. 如果要集成Javascript和Java,则可以使用Rhino。 See the example below for a better comprehension:
请参阅下面的示例以获得更好的理解:
test.js test.js
function test(array){
for(var i in array){
out.println(array[i]);
}
}
RhinoTest.java RhinoTest.java
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.Scriptable;
public class RhinoTest {
public static void main(String[] args) {
Context ctx = new ContextFactory().enterContext();
Scriptable scope = ctx.initStandardObjects();
try {
Object out = Context.javaToJS(System.out, scope);
scope.put("out", scope, out);
FileReader fr = new FileReader("test.js");
ctx.evaluateReader(scope, fr, "<cmd>", 1, null);
fr.close();
String[] strArray = {"name1","name2","name3"};
Object jsArray = Context.javaToJS(strArray, scope);
scope.put("jsArray", scope, jsArray);
ctx.evaluateString(scope, "test(jsArray)", "<cmd>", 1, null);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Context.exit();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.