javascript - 将字符串列表作为参数从 native java 代码传递给 javascript 函数

标签 javascript java list parameter-passing wikitude

我有一个 javascript 函数:

drawPath: function drawPathFn(nodeList){
        console.log(""+nodeList[1]);
},

调用这个函数的原生java代码是:

List<String> nodes = getShortestPath(s, d);
architectView.callJavascript("World.drawPath('"+nodes+"')");

节点列表充满了几个位置名称,但是当我尝试将此列表传递给 javascript 函数时,控制台输出只是:“[” for console.log(""+nodeList[0]); console.log(""+nodeList[1]);

的“S”

我想要的是当我调用 nodeList[0] 时,我希望它打印出来,例如“A楼”。 我怎样才能做到这一点?

最佳答案

您需要在 javascript 中将 JSObject 或字符串作为文字数组传递,即 "['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

关于javascript - 将字符串列表作为参数从 native java 代码传递给 javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33196303/

相关文章:

javascript - 如何用javascript锚定?

javascript - 带有 json 数据的动态 Highcharts

Javascript array.length 在 d3.csv() 函数中的 .push() 之后返回 0

Java MigLayout 在行中固定等宽

Java.util.Date 比较 ">="

Python-如何对文件中的值求和

html - 更改静态(列表项为图标

javascript - 一个简单的 .click() 在 Javascript 中不起作用

java - Android:单击列表项后如何使用不同的参数调用 onCreate()?

html - 在 ul 中缩进文本的右侧部分