0

I'm making a web application with a Java engine. How can I easily transfer my server-side data from the Java code to the client-side code (HTML, css, JavaScript,...). I know about servlets but I don't know how to properly work with them.

We have a fully functional Java engine, a GUI made in HTML and CSS, now we need to use the data in both ways.

Here is some code in my servlet constructor:

public GameServlet() {
    super();
    int numberOfPlayers = 4;
    int[] wins = {1,2,3,4};
    int[] losses = {1,2,3,4};
    String[] players = {"player1", "player2", "player3", "player4"};
    Game game = new Game(numberOfPlayers, players, wins, losses);
    System.out.println("test");
    System.out.println(players[3]);
    game.Start();
}

How can I access for example the players array in my JavaScript code?

halfer
  • 19,824
  • 17
  • 99
  • 186

1 Answers1

0

You could use AJAX to get data from the server from client side.

JQuery has a lot of helper functions to assist.

eg:

$.get('url/to/server-side/data').success(function(response) {
  console.log(response);
});

Have at how to do routing in java servlets.

You need to do a request like above, and then filter the url url/to/server-side/data to a server side method which responds the data.

Community
  • 1
  • 1
Rhys Bradbury
  • 1,699
  • 13
  • 24
  • please update your question with the code :) – Rhys Bradbury May 18 '16 at 13:04
  • Sorry, I'm new to posting questions! :) – Ward Adriaensen May 18 '16 at 13:07
  • Its okay :) - please comment on my answer if theres anything i can to to improve it. / if you dont understand anything. – Rhys Bradbury May 18 '16 at 13:08
  • Thank you for the quick response! I'm now trying to update the src attribute from cards on the playfield at the load event on the web application. I have a string array in my servlet with all the paths, now I need to route the array to my javascript to change the actual sources. Do you understand what I'm trying to do? – Ward Adriaensen May 18 '16 at 13:21
  • If you have been pointed in the right direction to move forward and you feel that this question is solved, please mark the answer as the answer to this question :) thanks – Rhys Bradbury May 18 '16 at 13:25
  • Do you have any idea how I can do that in jquery? Some example code? – Ward Adriaensen May 18 '16 at 13:32
  • You cannot get the Java array to JavaScript array, two different things. The interface or 'Agreement' is the routes themselves – Rhys Bradbury May 18 '16 at 13:34