I have some data that I need to send that is in a 2D array. I found that you send an array through post here here but i need to send a 2D array from my javascript using post to a java servlet. Is there a way to do this?
Asked
Active
Viewed 1,611 times
1 Answers
1
You can use exactly the same technique as the example you link to. This is because it uses JSON to serialise the data, so it can send entire JS data structures in one go. So, taking the example, but rebuilding it for a 2d array and tweaking it to send actual JSON:
var obj=[ [1.1, 1.2], [2.1, 2.2], [3.1, 3.2] ];
$.ajax({
url:"myUrl",
type:"POST",
dataType:'json',
success:function(data){
// codes....
},
data:JSON.stringify(obj),
contentType: 'application/json'
});
Then this will send a string to your server, like:
"[[1.1,1.2],[2.1,2.2],[3.1,3.2]]"
Your Java servlet will then have to deserialise this and use it however you want. In this example, the JSON will be sent as RAW post data; if you want to get it via the request object, you can do something like:
var obj=[ [1.1, 1.2], [2.1, 2.2], [3.1, 3.2] ];
$.ajax({
url:"myUrl",
type:"POST",
dataType:'json',
success:function(data){
// codes....
},
data: {json: JSON.stringify(obj)}
});
Then you should be able to get the JSON string from:
request.getParameterValues("json");

sifriday
- 4,342
- 1
- 13
- 24
-
So how would i deserialise the 2d array into a 2d string array on my servlet side? – user3704079 Nov 17 '14 at 16:05
-
Check out the json.org site - http://www.json.org/java/ ... you'll need to pull the JSON string out of the raw POST data. – sifriday Nov 17 '14 at 16:06