10

I have created a JS array like this var detailsArr = new Array(); and pushing some data into this array.

Now i push this array via Ajax to my Spring Controller like this

$.ajax({
            type: "POST",
            url: "submit",
            data: ({detailsArr : detailsArr }),
            success: function(html){
              alert( "Submitted");
                }
          });

At the Spring Controller side , i receive this array through the @RequestBody annotation. The Spring Controller method signature looks like this

public String submit(@RequestBody String body) 

But the array when received at the Spring Controller side is basically a String of this format

detailsArr[]=add&detailsArr[]=test1&detailsArr[]=test2&detailsArr[]=test3

I have to manually split this String to get the values, this is a cumbersome process. Is there any way in which I can get the array as it is , so that I just have to iterate over it to get the values.

4
  • 1
    Please add the method signature from your spring controller (with annotations) and a dump of detailsArr (console.log it or something like that) Commented Nov 25, 2011 at 7:04
  • The signature of my Spring controller looks like this public String submit(@RequestBody String body) and the dump of the detailsArr is like this detailsArr[]=add&detailsArr[]=test1&detailsArr[]=test2&detailsArr[]=test3 Commented Nov 25, 2011 at 7:08
  • after you read request body, u should get a string formatted in json, and then u should write or use a JsonUtil and convert your json string to class(array or what you want, what your format) Commented Nov 25, 2011 at 7:10
  • but the String format that I am getting does not seem to be formatted in JSON, I am not sure about this... but a hunch.... Commented Nov 25, 2011 at 7:12

2 Answers 2

11

you should pass your array to server in json format. And convert it by using Json to object converter. you can use Gson.

client side:

$.ajax({
            type: "POST",
            url: "submit",
            data:JSON.stringify(detailsArr),
            success: function(html){
              alert( "Submitted");
                }
          });

server side :

public String submit(@RequestBody String body){
//convert body to array using JSONLib, FlexJSON or Gson
}
Sign up to request clarification or add additional context in comments.

Comments

7

When passing it to your controller, pass it like this:

data:JSON.stringify(detailsArr);

At your controller, you can then decode the JSON received.

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.