ajax實現批量刪除
阿新 • • 發佈:2018-11-06
這幾天一直在學習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資料分割為陣列。