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

前端 未结 6 1161
独厮守ぢ
独厮守ぢ 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 20:05

    It is very simple passing such data to the Spring MVC controller, when you have in mind that data is being parsed from string. So if you want to get an array/list in the controller - pass a stringified version of the array:

    public String method(
            @RequestParam(value = "stringParam") String stringParam,
            @RequestParam(value = "arrayParam") List arrayParam) {
        ...
    }
    

    and the corresponding javascript with jQuery would be like:

    $.post("/urlToControllerMethod",
        {
            "stringParam" : "test",
            "arrayParam" : [1, 2, 3, "test"].toString()
        }
    );
    

    Note: the parameter type

    List arrayParam
    

    could be as well replaced with the array equivalent

    String[] arrayParam
    

提交回复
热议问题