Pass array data from javascript in browser to spring mvc controller using ajax

前端 未结 6 1155
独厮守ぢ
独厮守ぢ 2020-12-07 19:27

I would like to pass an array from javascript in web browser to a Spring MVC controller using AJAX

In javascript, I have

var a = [];
a[0] = 1;
a[1] =         


        
6条回答
  •  南笙
    南笙 (楼主)
    2020-12-07 19:43

    You can do this from the JavaScript side:

    $.ajax({
        type : "POST",
        url : "/myurl",
        data : {
            myArray: a //notice that "myArray" matches the value for @RequestParam
                       //on the Java side
        },
        success : function(response) {
           // do something ... 
        },
        error : function(e) {
           alert('Error: ' + e);
        }
    }); 
    

    Then on the Java side (in Spring 3), assuming that this method is mapped by /myurl:

    public String controllerMethod(@RequestParam(value="myArray[]") Integer[] myArray){
        ....
    }
    

    I believe the following will also work:

    public String controllerMethod(@RequestParam(value="myArray[]") List myArray){
        ....
    }
    

    Spring is smart enough to figure out how to do the binding.

    For multiple arrays, you might want to just have a command object:

    public class MyData {
        private List firstArray;
        private List secondArray;
        private List thirdArray;
    
        ...
        ...
    }
    

    Then on the JavaScript side:

    $.ajax({
        type : "POST",
        url : "/myurl",
        data : {            
            myData: {
               "firstArray": firstArray,
               "secondArray": secondArray,
               "thirdArray": thirdArray
            }            
        },
        success : function(response) {
           // do something ... 
        },
        error : function(e) {
           alert('Error: ' + e);
        }
    }); 
    

    On the Java side, you can bind using @ModelAttribute:

    public String controllerMethod(@ModelAttribute(value="myData") MyData myData) throws ParseException {
        ....
    }
    

    EDIT

    Changed the @RequestParam annotation to use myArray[] instead of just myArray, since this change appears to have been made in Spring after this answer was first posted.

提交回复
热议问题