简体   繁体   English

从Java调用.js文件中的JavaScript函数

[英]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: 我正在尝试做以下事情:

  1. Convert the Java String into a JavaScript array 将Java字符串转换为JavaScript数组
  2. Pass the JavaScript array to a JavaScript function in a different .js file. 将JavaScript数组传递给其他.js文件中的JavaScript函数。

Thanks, Sony 谢谢,索尼

If you want to use JavaScript in a Java application, you can use Rhino . 如果要在Java应用程序中使用JavaScript,可以使用Rhino

If you want to call client side JavaScript form a serverside Java web application, you can use DWR 's Reverse Ajax. 如果要从服务器端Java Web应用程序调用客户端JavaScript,则可以使用DWR的反向Ajax。

Good luck! 祝好运!

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.

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