1

To illustrate my point: I have Name Age and Address of 4 people

[Sam, 23, nj],
[Nome, 25, ny],
[Sim, 20, pa],
[Jack, 12, pa]

I need to send these 4 rows to the java side.

I am familiar with java side coding so I can retrieve 4 rows from a list etc etc. I am new to javascripts, so I was wondering how to put all this data into a variable and then send it to java, so that java understands i am sending 4 sets of data.

I wanted to do hashmap of objects, either way as I am a newbie i don't know which road to take.pls advice.

I know how to post data through ajax, only part i am struggling with is creating the arrAY so my java side can parse it.

Haran Murthy
  • 341
  • 2
  • 10
  • 30
  • 1
    The answer is in the question tags: use JSON to transform your JS array of arrays into a String. Then use JSON in Java to transform the string into an array of arrays. – JB Nizet Jul 30 '12 at 21:16
  • http://stackoverflow.com/questions/4656375/how-do-you-send-an-array-as-part-of-an-jquery-ajax-request – kosa Jul 30 '12 at 21:17

2 Answers2

1

You could serialize it to JSON so it looks something like this:

[{name: "Sam", age: 23, address: "nj"}, 
 {name: "Nome", age: 25, address: "ny"}]
Justin Ethier
  • 131,333
  • 52
  • 229
  • 284
  • @Justin-How about the java side, Do I need to add additional plugins to 1. identify the array of objects. 2. identify what the key is and the value – Haran Murthy Jul 30 '12 at 21:34
  • I suggest you use a JSON library on the Java side to deserialize your data. There is a list of libraries on http://json.org/ if you need to find one. – Justin Ethier Jul 30 '12 at 21:36
  • @Justin-I got the json string. How do I post the jsonstring "jsonText" to a servlet class. say my jsp is in folder /Source/jsp/X.jsp and the servlet is in /Source/java/Y.java – Haran Murthy Jul 31 '12 at 19:38
1

Java supports JSON objects: http://www.json.org/java/ Use these methods.

Convert the array format to a stored variable and use the stringify method.

var a = Array([Sam, 23, nj], [Nome, 25, ny], [Sim, 20, pa], [Jack, 12, pa]);
var jsonText = JSON.stringify(a);
//send jsonText to java via post after this

Edit

To answer below, my Java is rusty from disuse but you will need to use the libraries here https://github.com/douglascrockford/JSON-java, and send the client side data jsonText over post data:

<form method='post' action='/Source/jsp/X.jsp' id='jsonform'>
<input id='json' name='json' value=''>
</form>

Then run a script to fill the value of the input with jsonText and submit it.

Once that is done you can grab the POST data and deserialize it and use it in your Java program.

var input = document.getElementById('json');
var form = document.getElementById('jsonform');
input.value = jsonText;
form.submit();

For the Java part, you said you are familiar with it so I'll leave that bit to you.