最近需要批量删除的功能,其实和单个删除差不多,只不过批量删除需要将id集合分散,,因为我用的是spring的jpa,所以不需要写sql,只需要调用相应的接口就行,代码如下
1.接口:
public void del(String id);
2.接口实现:
public void del(String id) {
this.delete(TestDel.class, id);
}
3.Controller:
单个删除:
@RequestMapping("/delSingle")
@ResponseBody
public Layui deleSingle(HttpServletRequest request){
try {
String id = request.getParameter("id");
service.delete(TestDel.class, id);
return Layui.data("删除成功");
} catch (Exception e) {
return Layui.data("删除失败");
}
}
批量删除:
@RequestMapping("/delAll")
@ResponseBody
public Layui removes(String isStr){
if (isStr!=null &&!isStr.equals("")) {
String[] ids = isStr.split(",");
for (String id : ids) {
if(id!=null &&!id.equals("")){
service.del(id);
}
}
}
return Layui.data("删除成功");
}
4.前端页面
5.js:
layui.use(['table','layer','laytpl'],function(){
var table = layui.table;
var layer = layui.layer;
//单个删除
table.on('tool(resume)', function(obj){
var tableData = obj.data;
var layEvent = obj.event; //获得 lay-event 对应的值(也可以是表头的 event 参数对应的值)
var tr = obj.tr; //获得当前行 tr 的DOM对象
if(layEvent === 'del'){
layer.confirm('真的删除此行数据么', function(index){
$.ajax({
type: "POST",
dataType: "json",
url: "${base}/testDel/delSingle.htm" ,
data:{"id":tableData.id},
success: function (data) {
if(data.code==0){
obj.del();
table.reload();
}
layer.msg(data.msg);
}
});
});
}
});
//批量删除
$("#datadel").on('click',function(){
//获取选中状态
var checkStatus = table.checkStatus('tab');
//获取选中数量
var selectCount = checkStatus.data.length;
if(selectCount == 0){
layer.msg('批量删除至少选中一项数据',function(){});
return false;
}
layer.confirm('真的要删除选中的项吗?',function(index){
layer.close(index);
index = layer.load(1, {shade: [0.1,'#fff']});
var isStr="";
for(var i=0; i<selectCount; i++){
isStr = isStr + "," + checkStatus.data[i].id;
}
$.ajax({
type:'post',
data:{"isStr":isStr},
url:'${base}/testDel/delAll.htm',
success:function(data){
if(data.code==0){
$('#seach').click();
}
layer.close(index);
layer.msg(data.msg);
},error:function(code){
parent.layer.msg('操作失败!',{icon: 5,time:1000});
}
});
})
});
});