浏览 1174 次
|
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
|---|---|
| 作者 | 正文 |
|
时间:2007-11-01
1. package co.test;
2.
3. import java.io.FileReader;
4. import java.io.LineNumberReader;
5.
6. import org.mozilla.javascript.Context;
7. import org.mozilla.javascript.Function;
8. import org.mozilla.javascript.Scriptable;
9.
9.public class JSExploration
9.{
9. private Context cx;
9.
9. private Scriptable scope;
9.
9. public JSExploration()
9. {
9. this.cx = Context.enter();
9. this.scope = cx.initStandardObjects();
9. }
9.
9. public Object runJavaScript(String filename)
9. {
9. String jsContent = this.getJsContent(filename);
9. Object result = cx.evaluateString(scope, jsContent, filename, 1, null);
9. return result;
9. }
9.
9. private String getJsContent(String filename)
9. {
9. LineNumberReader reader;
9. try
9. {
9. reader = new LineNumberReader(new FileReader(filename));
9. String s = null;
9. StringBuffer sb = new StringBuffer();
9. while ((s = reader.readLine()) != null)
9. {
9. sb.append(s).append("\n");
9. }
9. return sb.toString();
9. }
9. catch (Exception e)
9. {
9. // TODO Auto-generated catch block
9. e.printStackTrace();
9. return null;
9. }
9. }
9.
9.
9. public Scriptable getScope()
9. {
9. return scope;
9. }
9.
9. public static void main(String[] args)
9. {
9. String filename = System.getProperty("user.dir") + "/jsmap.js";
9. JSExploration jsExploration = new JSExploration();
9. Object result = jsExploration.runJavaScript(filename);
9. Scriptable scope = jsExploration.getScope();
9.
9. Function sum = (Function) scope.get("sum", scope);
9. Function isPrime = (Function)sum.call(Context.getCurrentContext(), scope, sum, new Object[] {2,8});
9. Object ss = isPrime.call(Context.getCurrentContext(), sum, isPrime, new Object[] {2,8});
9. System.out.println(Context.toString(ss));
9.
9. }
9. }
试验了一个java 调用 javascript 的例子,如果把jsmap.js中的与this 有关的代码注销的话程序就可以正常运行。不住销掉的话就会报个运行时错误。。。 js 代码如下(有关this 的代码已注销): 1. function sum(x, y) {
2.// this.formulaeObject = null;
3.// this.formulaeObject["vager"] = function (c, d) {
// return (c + d)/2;
4.// };
5. var vager = 1000;
6. return function (x,y){return x + y + vager;} ;
7. }
8.
声明:JavaEye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
|
|
| 返回顶楼 | |
|
时间:2008-01-11
假如在javascript用Document.getElementById()之类的返回一个object然后穿到java中,我这是个思路,并没有动手
试验,最近我也在弄这个东西,不过我用javax.script.这个包,能执行javascript的方法,我郁闷的是 如何把“用Document.getElementById()之类的返回一个object然后穿到java中”,。。。 |
|
| 返回顶楼 | |



