SpringMVC如何接受 js jquery ajax 的数组参数传值
1.接受字符串数组
Array arr = new Array();
$(".pic_li.active img[data]").each(function(){
arr.push($(this).attr("data"));
});
$.post(ctx+"/photo/up", {ids: arr}, function(response){
if(response.state==1){
console.log.('成功')
}else{
console.log.('失败')
}
})
$.ajax({
url : "/photo/up",
type : "post",
data :{ids:arr},
success : function(data) {
if(response.state==1){
console.log.('成功')
}else{
console.log.('失败')
}
}
});
后台 SpringMVC 接受: 注意参数ids[] ,多了“[]”。没有的话接收不到
/*
* 提交
*/
@RequestMapping(value ="up",method = RequestMethod.POST)
@ResponseBody
public Result<Photo> indexPut(Model model,HttpServletRequest request,
@RequestParam(value = "ids[]") String[] ids) {
if(ids!=null&ids.length>0)
return new Result<Photo>成功("",null);
return new Result<Photo>("失败",null);
}
或者 List 接受
/*
* 提交
*/
@RequestMapping(value ="up",method = RequestMethod.POST)
@ResponseBody
public Result<Photo> indexPut(Model model,HttpServletRequest request,
@RequestParam(value = "ids[]") List ids) {
if(ids!=null&ids.size()>0)
return new Result<Photo>成功("",null);
return new Result<Photo>("失败",null);
}
2.接受数组对象:
<script type="text/javascript">
$(document).ready(function(){
var saveDataAry=[];
var data1={"userName":"test","address":"gz"};
var data2={"userName":"ququ","address":"gr"};
saveDataAry.push(data1);
saveDataAry.push(data2);
$.ajax({
type:"POST",
url:"user/saveUser",
dataType:"json",
contentType:"application/json",
data:JSON.stringify(saveData),
success:function(data){
}
});
});
</script>
java代码
@RequestMapping(value = "saveUser", method = {RequestMethod.POST }})
@ResponseBody
public void saveUser(@RequestBody List<User> users) {
userService.batchSave(users);
}