这几天一直在学习ajax,实现了用ajax来批量删除数据。
HTML
<thead>
<tr>
<th class="table-check">
<input id="allchk" onclick="allcheck();" type="checkbox" />
</th>
<th class="table-id">ID</th>
<th class="table-title">photo</th>
</tr>
</thead>
<tbody id="Cinfor_tbody">
<c:forEach var="project" items="${list }">
<tr id="tr_${project.id }">
<td class="table-check">
<input name="ids" value="${project.id }" type="checkbox" />
</td>
<td class="table-id">${project.id }</td>
<td class="table-proficiency">${project.category.categoryName }</td>
</tr>
</c:forEach>
</tbody>
type属性为checkbox的input多选框的name为ids,value为数据的id,我们要根据这个id来进行删除。
ajax
//全选,这个方法实现点击id为allchk的input时,下列的所有多选框变为checked的状态
function allcheck(){
if ($("#allchk").is(':checked')) {
$("input[name='ids']").prop("checked",true);
}else if($("#allchk").is(':checked')==false){
$("input[name='ids']").prop("checked",false);
}
}
//批量删除
$(function(){
$("#deleteSkills").click(function(){
//判断是否至少选择一项
var checkedNum = $("input[name='ids']:checked").length;
if(checkedNum==0){
alert("请至少选择一项");
return;
}
if(confirm("确定要删除所选项目?")){
//这个数组存储要删除的数据的id
var checkedList = new Array();
//每一个被选中的name为ids的input标签
$("input[name='ids']:checked").each(function(){
checkedList.push($(this).val());//将id存入数组
});
$.ajax({
type:"post",
dataType:"json",
url:"deleteProjects.action",//不同页面只用更改action即可
async:true,
//数组的toString里的id是用","分隔开的,例如数组{"1","2","3"},同String后为"1,2,3"
data:{"deleteList":checkedList.toString()},
success:function(data){
if(data==1){
for(var i=0;i<checkedList.length;i++){
$("#tr_"+checkedList[i]).remove();//ajax动态移除
}
alert("删除成功");
}else{
alert("删除失败");
}
},
error:function(){
alert("error");
}
})
}
})
})
Controller
/*
* 通过id批量删除project
*/
@RequestMapping("/deleteProjects.action")
@ResponseBody
public String deleteProjects(String deleteList){
//因为传递的deleteList为带","的字符串,所以需要消掉分隔符转为数组
String[] ids = deleteList.split(",");
for(String id:ids){
projectService.deleteProjectById(Integer.parseInt(id));
}
return "1";
}
这里需要特别注意的就是我们要把ajax传过来的String数据分割为数组。