How do I pass an array to a Spring controller method with jquery ajax

后端 未结 3 1547
孤城傲影
孤城傲影 2021-02-13 18:44

Here\'s my ajax call:

 $.ajax({
     type: \'GET\',
     url: contextPath + \'/test/location\',
     data: {\'objectValues\': object.objectValues },
     datatyp         


        
3条回答
  •  情歌与酒
    2021-02-13 19:29

    There are multiple ways to do this, depending on which component you think is sending or receiving data in the incorrect format (or which component you have access to modify).

    If you believe the default way that jQuery sends data is correct, modify your controller appropriately (note you'll need to change both on the method signature and the annotation if you use both):

    @RequestMapping(value = "/location", method=RequestMethod.GET, params="objectValues[]")  
    public @ResponseBody String loadLocation(@RequestParam(value="objectValues[]", required=false) String[] objectValues) {  
        ...  
    }
    

    If you believe Spring functions correctly, but data sent from jQuery is incorrect, modify jQuery:

    $.ajax({
        traditional: true,
        ...  
    });
    

    See more on jQuery AJAX settings for the traditional setting.

    I myself think it is cleaner to modify the way jQuery sends data; it keeps my Controller syntax looking like I want.

提交回复
热议问题