admin管理员组文章数量:1327694
By using Java Sripting API, I am able to execute JavaScript within Java. However, can someone please explain how to capture the return value from a JS in Java? In the example below, can I invoke the script2 using
inv.invokeFunction("getValue", "Number", "2);
How can I get the return value from script2?
import javax.script.*;
public class InvokeScriptFunction {
public static void main(String[] args) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// JavaScript code in a String
String script1 = "function hello(name) {print ('Hello, ' + name);}";
String script2 = "function getValue(a,b) { if (a==="Number") return 1;
else return b;}";
// evaluate script
engine.eval(script1);
engine.eval(script2);
Invocable inv = (Invocable) engine;
inv.invokeFunction("hello", "Scripting!!" ); //This one works.
}
}
By using Java Sripting API, I am able to execute JavaScript within Java. However, can someone please explain how to capture the return value from a JS in Java? In the example below, can I invoke the script2 using
inv.invokeFunction("getValue", "Number", "2);
How can I get the return value from script2?
import javax.script.*;
public class InvokeScriptFunction {
public static void main(String[] args) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// JavaScript code in a String
String script1 = "function hello(name) {print ('Hello, ' + name);}";
String script2 = "function getValue(a,b) { if (a==="Number") return 1;
else return b;}";
// evaluate script
engine.eval(script1);
engine.eval(script2);
Invocable inv = (Invocable) engine;
inv.invokeFunction("hello", "Scripting!!" ); //This one works.
}
}
Share
Improve this question
asked Oct 28, 2013 at 3:30
user2300206user2300206
733 silver badges7 bronze badges
1
- if i write above code in servlet then can we say that JavaScript is running at serverside? – Prashant Shilimkar Commented Oct 28, 2013 at 4:10
1 Answer
Reset to default 6This is how you will get that return value.
String returnValue = (String)inv.invokeFunction("hello", "Scripting!!" );
Same for script 2, just change the call accordingly.
The invokeFuntion method from Invocable returns an Object. So, we must type-cast it to the appropriate type before using it.
Reference
本文标签: Capture the javascript return value in javaStack Overflow
版权声明:本文标题:Capture the javascript return value in java - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742219225a2435136.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论