我有一个javascript函数:
drawPath: function drawPathFn(nodeList){
console.log(""+nodeList[1]);
},
并且调用此函数的本机java代码是:
List<String> nodes = getShortestPath(s, d);
architectView.callJavascript("World.drawPath('"+nodes+"')");
节点列表中填充了多个位置名称,但是当我尝试将此列表传递给javascript函数时,控制台输出只是:“[{1}}为”,console.log(""+nodeList[0]);
为“S” / p>
我想要的是当我调用nodeList [0]时,我希望它打印出来,例如“建筑A”。 我怎么能做到这一点?
答案 0 :(得分:0)
您需要在javascript中将JSObject或String作为文字数组传递,即"['str0','str1']"
。
以下是如何使用JSObject:
//first we need an Iterator to iterate through the list
java.util.Iterator it = nodes.getIterator();
//we'll need the 'window' object to eval a js array, you may change this
//I dont know if you are using an applet or a javaFX app.
netscape.javascript.JSObject jsArray = netscape.javascript.JSObject.getWindow(YourAppletInstance).eval("new Array()");
//now populate the array
int index = 0;
while(it.hasNext()){
jsArray.setSlot(index, (String)it.next());
index++;
}
//finaly call your function
netscape.javascript.JSObject.getWindow(YourAppletInstance).call("World.drawPath",new Object[]{jsArray});
以下是使用文字字符串的方法:
java.util.Iterator it = nodes.getIterator();
int index = 0;
String literalJsArr = "[";
//populate the string with 'elem' and put a comma (,) after every element except the last
while(it.hasNext()){
literalJsArr += "'"+(String)it.next()+"'";
if(it.hasNext() ) literalJsArr += ",";
index++;
}
literalJsArr += "]";
architectView.callJavascript("World.drawPath("+literalJsArr+")");
参考:
http://www.oracle.com/webfolder/technetwork/java/plugin2/liveconnect/jsobject-javadoc/netscape/javascript/JSObject.html https://docs.oracle.com/javase/tutorial/deployment/applet/invokingJavaScriptFromApplet.html