magicbacon
magicbacon

Reputation: 331

How to accept JavaScript Array parameter in Spring MVC Controller in a jQuery ajax call?

I hava a jQuery ajax call like this:

var arr = ["a", "b", "c"];
$.get("/test", {testArray: arr}, function(data) {
    alert(data);
});

server side:

@RequestMapping(value = "/test", method = RequestMethod.GET)
public String addAnotherAppointment(
        HttpServletRequest request,
        HttpServletResponse response,
                    @RequestParam("arr") arr,
        Model model,
        BindingResult errors) {
}

So how do I receive the parameter?

Thanks.

Upvotes: 0

Views: 21212

Answers (2)

Oh Jong Am
Oh Jong Am

Reputation: 136

If you use spring 3.0++,use "@ResponseBody" annotation.

Do you want to send a json request, and receive a response from json? If so, you'll change your code like this.

var list = {testArray:["a", "b", "c"]};
$.ajax({
    url : '/test',
    data : $.toJSON(list),
    type : 'POST', //<== not 'GET',
    contentType : "application/json; charset=utf-8",
    dataType : 'json',
    error : function() {
        console.log("error");
    },
    success : function(arr) {
        console.log(arr.testArray);
        var testArray = arr.testArray;
         $.each(function(i,e) {
             document.writeln(e);
         });
    }
  });

server side:

  1. create your own "Arr" class.

    public class Arr {
     private List<String> testArray;
     public void setTestArray(List<String> testArray) {
         this.testArray = testArray;
     }
     public List<String> getTestArray() {
         return testArray;
     }
     }
    

    and

    @RequestMapping(value = "/test", method = RequestMethod.POST)
    @ResponseBody// <== this annotation will bind Arr class and convert to json response.
       public Arr addAnotherAppointment(
       HttpServletRequest request,
        HttpServletResponse response,
        @RequestBody Arr arr, 
        Model model,
        BindingResult errors) {
            return arr;
    }
    

Upvotes: 3

Kris
Kris

Reputation: 1902

Change @RequestParam("arr") arr, to @RequestParam("testArray") String[] arr

Also change your HTTP method from get to post

Please note @RequestParam value must match the parameter name send from the jquery ajax . In your case the param name is testArray and value is arr

Upvotes: 1

Related Questions