javascript中如何传个数组到后台String [ ] 接收?
后端狗实在折腾,求,想写个table的多行记录选择时数组形式传到后台
百度出来多为说用逗号隔离然后一个string接收,不能直接用string[ ] 么? 展开
2020-04-28
方法一:
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.后台处理
@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.后台处理
@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不同。
原文链接:https://blog.csdn.net/zhaohuijiadelu/article/details/54408324