alex007 alex007 - 1 year ago 103
Java Question

send data in arraylist to an array in javascript

I want to send the the data in my arraylist in java to an array in js. I searched on the web but I am still not sure how to do it. I saw someone tried to do it by writing the js and javacode together. How can I do it separately? In other words, java code and js code are separate. Please the picture below.
I want to use javaFx or something that does not need to go through the internet like jsp.
Thank you so much.

js and java code are seperate

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;

public void start(Stage stage) throws Exception {
WebView myWebView = new WebView();
WebEngine engine = myWebView.getEngine();
ArrayList<String> arr = new ArrayList<String>();

send = new Button("send_to_js");
send.setOnAction(new EventHandler<ActionEvent>() {

public void handle(ActionEvent event) {

VBox vb = new VBox();
vb.getChildren().addAll(myWebView, send);
Scene scene = new Scene(vb, 500, 500);

public static void main(String[] args) {


$(document).ready(function() {
/* how do I put the data into the array*/
var receiver = [...];

Answer Source

Yep, Java and Javascript are 2 different languages and thus it is not possible for you to directly pass the Java data structures around freely between both worlds.

The usual approach for solving such a problem is through serialization. That is, you would encapsulate your data from the java world into some data format e.g. XML or JSON and then from your javascript process, parse the serialized data into Javascript object.

For instance let say you have a simple Java class call Car with properties "color" and "Brand" and you have an array of Car.

Car[] cars = new Car[3];

You could represent this in JSON as;

    cars: [
        0: { brand: "Honda", color: "Red" },
        1: { brand: "BMW", color: "Black" },
        2: { brand: "Toyota", color: "Yellow" }

Then with this JSON document, you could then parse it into a javascript array with objects.

As for how you can pass a JSON document around from 1 process to another or even from macihne to machine, there are any ways you could do it.

You can either serialize the JSON data as a flat file and then read the content from another side or typically people just make use of the web service technology.

Let me know if this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download