5

的脚本Arrayint我希望传入Spring Controller. 但我不断得到

400 bad request.

如果我js array

array = [1,2,3,4]
array -> 400 bad request
JSON.Stringify(array) -> I will get [1,2,3,4]

    $.ajax({//jquery ajax
                data:{"images": array},                
                dataType:'json',
                type:"post",
                url:"hellomotto"
                ....
            })

当我循环string List..第一个元素将是'[1'

@RequestMapping(value = "/hellomotto", method = Request.POST)
public void hellomotto(@RequestParam("images") List<String> images){
 sysout(images); -> I will get [1,2,3,4]
}

公共空白

我可以知道如何正确执行此操作吗?我尝试了不同的组合

4

3 回答 3

7

以下是一个工作示例:

Javascript:

$('#btn_confirm').click(function (e) {

    e.preventDefault();     // do not submit the form

    // prepare the array
    var data = table.rows('.selected').data();
    var ids = [];
    for(var i = 0; i < data.length; i++) { 
        ids.push(Number(data[i][0]));
    }

    $.ajax({
        type: "POST",
        url: "?confirm",
        data: JSON.stringify(ids),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data){
            alert(data);
        },
        failure: function(errMsg) {
            alert(errMsg);
        }
    });
});

控制器:

@RequestMapping(params = "confirm", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody int confirm(@RequestBody Long[] ids) {
    // code to handle request
    return ids.length;
}
于 2015-10-06T12:40:21.337 回答
0

@RequestParam 用于绑定请求参数,所以如果你做类似的事情

@RequestMapping(value = "/hellomotto", method = Request.POST)
public void hellomotto(@RequestParam("image") String image){
     ...
}

并且您确实发布到/hellomotto?image=test,hellomotto 方法中的图像变量将包含“test”

你想要做的是解析 Request body ,所以你应该使用 @RequestBody 注释:

http://docs.spring.io/spring/docs/3.0.x/reference/mvc.html#mvc-ann-requestbody

它使用杰克逊实验室(因此您必须将其作为您的依赖项包含在内)将 json 对象解析为 java 对象。

于 2013-10-18T04:09:23.547 回答
0

我认为你希望通过 ajax 调用 Ajax,你正在发送整数列表,所以在春天你的控制器将是

@RequestMapping(value = "/hellomotto", method = Request.POST)
@ResponseBody
public void hellomotto(@RequestParam("images") List<Integer> images){
 sysout(images); -> I will get [1,2,3,4]
}

*您的代码中缺少@ResponseBody

于 2013-10-18T08:35:04.457 回答