我想将java中的数组列表中的数据发送到js中的数组。我在网上搜索过,但我仍然不知道该怎么做。我看到有人尝试通过js和javacode一起写来做到这一点。我怎样才能单独做呢?换句话说,java代码和js代码是分开的。请看下图。 我想使用 javaFx 或不需要通过互联网(例如 jsp)的东西。 太感谢了。
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import java.util.ArrayList;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
public class SendData extends Application{
Button send;
@Override
public void start(Stage stage) throws Exception {
WebView myWebView = new WebView();
WebEngine engine = myWebView.getEngine();
ArrayList<String> arr = new ArrayList<String>();
arr.add("string1");
arr.add("string2");
arr.add("string3");
arr.add("string4");
arr.add("string5");
send = new Button("send_to_js");
send.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
/*?*/
}
});
VBox vb = new VBox();
vb.getChildren().addAll(myWebView, send);
Scene scene = new Scene(vb, 500, 500);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
$(document).ready(function() {
/* how do I put the data into the array*/
var receiver = [...];
});
最佳答案
我对 JavaFX 知之甚少,但是你能使用WebEngine.executeScript
吗? ?
// JSON-ify the ArrayList
String json = "[";
for (int i = 0; i < arr.size(); i++) {
if (i != 0) json += ",";
json += "'"+arr[i]+"'"; // NOTE: this doesn't escape special characters in arr[i]
}
json += "]";
// pass it to some JS function?
engine.executeScript("someFunction("+json+")");
关于javascript - 将 arraylist 中的数据发送到 JavaScript 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40813808/