文章目录
One day, One word: 只有能面对现实,你才能超越现实
index:经常利用ajax向后端传多个数据,最常见的就是批量删除的情况,一次性传多个id,怎么传?后端如何接受;批量修该需要传多个属性的多个值,如何传递?
ajax向后端传多个值
一、拼串
- 这里以批量删除为例
1.把需要的数据按照指定格式拼串
- 通过主键批量删除数据,这里的数据格式为
id=5&id=6&id=7
- 注意这时候拼串用到的属性名为id
var idStr = "";
$.each(selectCheckbox,function(i,n){
if(i!=0){
idStr += "&"
}
// id=5&id=6&id=7
idStr += "id="+n.id;
});
alert(idStr);
2.发起ajax请求,批量删除
- 此处省略对按钮绑事件和调用函数的操作
$.ajax({
type : "POST",
data : idStr,
url : "${APP_PATH}/user/doDeleteBatch.do",
beforeSend : function(){
return true;
},
success : function(result){
if(result.success){
window.location.href="${APP_PATH}/user/toIndex.htm"
}else {
layer.msg(result.message, {time:1000, icon:5, shift:6});
}
},
error : function(){
layer.msg("删除用户失败", {time:1000, icon:5, shift:6});
}
});
3.后台处理数据
(1)控制器拦截处理
- 注意:上面传来的值是个字符串,springmvc解析后应该是个结合,这个数组的属性名就是上面拼串的属性名id
@ResponseBody
@RequestMapping("/doDeleteBatch")
public Object doDeleteBatch(Integer[] id){
AjaxResult result = new AjaxResult();
try {
int count = userService.deleteBatchUser(id);
result.setSuccess(count==id.length);
} catch (Exception e) {
result.setSuccess(false);
e.printStackTrace();
result.setMessage("删除数据失败");
}
return result;
}
(2)业务层的实现类
public int deleteBatchUser(Integer[] ids) {
int totalCount = 0;
for (Integer id : ids) {
int count = userMapper.deleteByPrimaryKey(id);
totalCount += count;
}
if(totalCount != ids.length){
throw new RuntimeException("批量删除失败");
}
return totalCount;
}
- mapper就是调用通过主键id删除的方法,这里省略
(3)扩展
-
拼串的时候也可以是多个属性拼串的,比如需要批量增加的时候,这个时候就有可能会涉及到多个属性,这个手就可以这样拼串
id=5&id=6&id=7&name='tom'&name='jack'&name='lucy'
控制器拿到这个数据的事就就会创建两个数组,名称分别为id和name,对这两个数组里的数据按照索引取出对应的值,就可以用来批量增加了。
二、把传递的值用对象封装
1.创建一个类,用于数据的封装
- 在工具类的包下创建一个Data.java
- 根据需要设定泛型的类型
- 给出getter和setter方法
public class Data {
private List<User> userList = new ArrayList<User>();
private List<User> datas = new ArrayList<User>();
private List<Integer> ids;
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
public List<User> getDatas() {
return datas;
}
public void setDatas(List<User> datas) {
this.datas = datas;
}
public List<Integer> getIds() {
return ids;
}
public void setIds(List<Integer> ids) {
this.ids = ids;
}
}
2.前端数据的封装
- 把数据封装成一个json对象
var jsonObj = {};//定义一个json对象
$.each(selectCheckbox,function(i,n){
jsonObj["datas["+i+"].id"] = n.id;//把数据封装成后台定义的格式类型,方便取出
jsonObj["datas["+i+"].username"] = n.name;//把数据封装成后台定义的格式类型,方便取出
});
- 通过ajax请求发送到后端
$.ajax({
type : "POST",
//data : idStr,
data : jsonObj,
url : "${APP_PATH}/user/doDeleteBatch.do",
beforeSend : function(){
return true;
},
success : function(result){
if(result.success){
window.location.href="${APP_PATH}/user/toIndex.htm"
}else {
layer.msg(result.message, {time:1000, icon:5, shift:6});
}
},
error : function(){
layer.msg("删除用户失败", {time:1000, icon:5, shift:6});
}
});
3.后台数据的处理
(1)控制器接收数据
- 把接收到的数据用Data类封装
@ResponseBody
@RequestMapping("/doDeleteBatch")
public Object doDeleteBatch(Data data){
AjaxResult result = new AjaxResult();
try {
int count = userService.deleteBatchUserByVO(data);
result.setSuccess(count==data.getDatas().size());
} catch (Exception e) {
result.setSuccess(false);
e.printStackTrace();
result.setMessage("删除数据失败");
}
return result;
}
(2)方式一:业务层的实现类
- 通过data对象进行封装得到的值
public int deleteBatchUserByVO(Data data) {
return userMapper.deleteBatchUserByVO(data);//传data对象
}
(3)方式一:映射文件
-
方式一:从data对象里拿到datas
-
这里遍历的是data对象里的datas属性,Mybatis做解析可以直接拿到
<delete id="deleteBatchUserByVO" parameterType="java.lang.Integer">
/*delete from t_user where id in (1,2,3)*/
delete from t_user
where id in
<foreach collection="datas" open="(" close=")" separator="," item="user">
#{user.id}
</foreach>
</delete>
(4)方式二:业务层的实现类
- 传data集合
public int deleteBatchUserByVO(Data data) {
return userMapper.deleteBatchUserByVO(data.getDatas());//传data集合
}
(5)方式二:mapper
- 此时,拿到的是一个集合
int deleteBatchUserByVO(List<User> userList);
(6)映射文件
- 此时遍历的集合名不能写为userList,Mybatis把集合的名设为list,如果想用userList,需要在mapper类中加上@Param(“userList”)
<delete id="deleteBatchUserByVO" parameterType="java.lang.Integer">
/*delete from t_user where id in (1,2,3)*/
delete from t_user
where id in
<foreach collection="list" open="(" close=")" separator="," item="user">
#{user.id}
</foreach>
</delete>
- 注意Mybatis的规定:
- 如果mapper接口参数类型为Collection集合,那么,可以使用list来获取这个集合的参数
- 如果mapper接口参数类型为Array数组,那么,可以使用array来获取这个数组的参数
elete from t_user
where id in
<foreach collection="list" open="(" close=")" separator="," item="user">
#{user.id}
</foreach>
</delete>
- 注意Mybatis的规定:
- 如果mapper接口参数类型为Collection集合,那么,可以使用list来获取这个集合的参数
- 如果mapper接口参数类型为Array数组,那么,可以使用array来获取这个数组的参数