Reputation: 907
So I have a little issue here as described. In the following first example I'm passing a simple array which is working. If I want to pass an array of arrays in the second example, it isn't working anymore. Any suggestions?
This works:
JS
var myArrayOfStrings = ["x", "y"];
function createConsumer(){
$.ajax({
type: "POST",
url: "/save",
data: { myArray: myArrayOfStrings }
});
}
Controller
@RequestMapping(value = "/save", method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody void Submit(@RequestParam("myArray[]") String[] name) {
System.out.println(name[0]);
}
The following solution isn't working, why? I just want to pass an Array of Arrays instead of a "simple Array". How will it work?
JS
var myArrayOfArrays = [["x", "y"],["x", "y"]];
function createConsumer(){
$.ajax({
type: "POST",
url: "/save",
data: { myArray: myArrayOfArrays }
});
}
Controller
@RequestMapping(value = "/save", method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody void Submit(@RequestParam("myArray[][]") String[][] name) {
System.out.println(name[0][0]);
}
Upvotes: 2
Views: 2123
Reputation: 58
I think you should serialize your nested array with JSON.stringify()
before you pass it with AJAX.
var myArrayOfArrays = [["x", "y"],["x", "y"]];
function createConsumer(){
$.ajax({
type: "POST",
url: "/save",
data: JSON.stringify({ myArray: myArrayOfArrays })
});
}
Kind regards.
Upvotes: 3
Reputation: 907
This solution worked.
var myArrayOfArrays = [["x", "y"],["x", "y"]];
function createConsumer(){
$.ajax({
contentType: "application/json",
type: "POST",
url: "/save",
data: JSON.stringify(myArrayOfArrays)
});
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
public @ResponseBody void Submit(@RequestBody String[][] name) {
System.out.println(name[0][0]);
}
Upvotes: 1