Pass parameter to JavaScript through Java code -
i'm trying define generic formula, e.g. "a+b" , use pass parameters. ideas how make thing work?
scriptenginemanager manager = new scriptenginemanager(); scriptengine engine = manager.getenginebyname("javascript"); string formula="a+b"; engine.put("formula", formula); engine.put("a", "3"); engine.put("b", "4"); res = engine.eval("r = formula").tostring(); system.out.println(res);
the output of above code "a+b" , not 7 expected.
to bind variable names values, use bindings.
i thing following code solves question:
scriptenginemanager manager = new scriptenginemanager(); scriptengine engine = manager.getenginebyname("javascript"); string formula="a+b"; bindings bindings = engine.createbindings(); bindings.put("a", 3); bindings.put("b", 4); engine.setbindings(bindings, scriptcontext.engine_scope); object res = engine.eval(formula); system.out.println(res.tostring());
Comments
Post a Comment