美文网首页
js传递数组到后台

js传递数组到后台

作者: 明月888 | 来源:发表于2018-07-04 19:29 被阅读0次

今天一位同事碰到了这个问题,相互讨论了下,记录下备忘
其他参考 https://blog.csdn.net/white_ice/article/details/52605302
方法一:
1.使用JSON.stringify 将数组对象转化成json字符串;

var array = ["1", "2"];
$.ajax({  
    type : 'POST',  
    url: path + '/check/testPost',  
    contentType : "application/json" ,
    data : JSON.stringify(array), 
    success : function(data) {  

    }  
}); 

2.传输过程中参数


image.png

3.后台处理

@RequestMapping(value = "/testPost", method = {RequestMethod.POST})
public void testPost(@RequestBody String[] array) throws IOException {
    for (String string : array) {
        System.out.println(string);
    }
    return ;
}

方法二:
1.前端不做处理:

var array = ["1", "2"];
$.ajax({  
    type : 'POST',  
    url: path + '/check/testPost',
    contentType: "application/x-www-form-urlencoded",
    data: {"array": array},
    success : function(data) {  
    }  
});  

2.传输过程中参数


image.png

3.后台处理

@RequestMapping(value = "/testPost", method = {RequestMethod.POST})
public void testPost(HttpServletRequest req) throws IOException {
    String[] array = req.getParameterValues("array[]");
    for (String string : array) {
        System.out.println(string);
    }
    return ;
}

注:两种post请求的content-type不同。

相关文章

网友评论

      本文标题:js传递数组到后台

      本文链接:https://www.haomeiwen.com/subject/kpsyuftx.html