Justin Lange
Justin Lange

Reputation: 907

Pass array of arrays from JavaScript to Spring MVC controller using AJAX

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

Answers (2)

theroka
theroka

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

Justin Lange
Justin Lange

Reputation: 907

This solution worked.


JavaScript:

var myArrayOfArrays = [["x", "y"],["x", "y"]];

function createConsumer(){
    $.ajax({
         contentType: "application/json",
         type: "POST",
         url: "/save",
         data: JSON.stringify(myArrayOfArrays)
    });
}

Controller:

@RequestMapping(value = "/save", method = RequestMethod.POST)
public @ResponseBody void Submit(@RequestBody String[][] name) {
    System.out.println(name[0][0]);
}

Upvotes: 1

Related Questions