2

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]);
}

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

How would I change the controller?
@RequestParam("myArray") String name
1

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]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.