springboot + ajax + mybatis 實現批量刪除


實現思路:

  1. checkbox全選獲取批量刪除的id數組

  2. ajax以字符串的形式將id數組傳給控制器

  3. 控制器將字符串分割成List數組作為參數傳給mapper

 

具體代碼:

  1. 前端代碼

<table>
    <thead>
        <tr>
            <th>#</th>
            <th>id</th>
            <th>文件名</th>
            <th>文件類型</th>
            <th>上傳時間</th>
            <th>上傳用戶</th>
            <th>文件大小</th>
        </tr>
    </thead>
    <tbody>
        <tr th:each="resource:${resources}">
            <td>
                <input type="checkbox" name="checkId" id="checkId" th:value="${resource.id}"/>
            </td>
            <td th:text="${resource.id}">Row 1 Data 1</td>
            <td th:text="${resource.fileName}">Row 1 Data 2</td>
            <td th:text="${resource.fileType}">Row 1 Data 1</td>
            <td th:text="${resource.fileTime}">Row 1 Data 2</td>
            <td th:text="${resource.fileUploader}">Row 1 Data 1</td>
            <td th:text="${resource.fileSize}">Row 1 Data 2</td>
        </tr>
    </tbody>
</table><br>
<input type="checkbox"  name="selectAll" id="selectAll" onclick="selectAll(this);">全選&emsp;
<button type="button"  onclick="deleteLogic();">批量刪除</button>

 

  2. js代碼

/**
 * checkbox全選/全不全
 * @param checkbox
 */
function selectAll(checkbox) {
    $('input[name="checkId"]').prop('checked', $(checkbox).prop('checked'));
}

/**
 * 批量刪除
 */
function deleteLogic() {

    var checkNum = $("input[name='checkId']:checked").length;

    if(checkNum==0){
        alert("至少選擇一項");
        return;
    }

    if(confirm("確定要刪除嗎?")){
        var checkList = new Array();
        $("input[name='checkId']:checked").each(function () {
            checkList.push($(this).val())
        });
    }
    
    $.ajax({
        url:"/deleteAll",
        type:"post",
        data:{
            checkList:checkList.toString()
        },
        datatype:"json",
        success:function (data) {
            location.reload();
            alert("刪除成功!")
        },
        error:function (msg) {
            alert("刪除失敗!")
        }
    })
}

 

  3. Controller代碼

@PostMapping("/deleteAll")
@ResponseBody
public String deleteAll(String checkList){

    System.out.println("==>"+checkList);

    String[] strs = checkList.split(",");
    List<Integer> ids = new ArrayList<>();

    for(String str:strs){
        ids.add(Integer.parseInt(str));
    }

    resourcesService.deleteAll(ids);

    return "success";
}

 

  4. mapper.xml代碼

<delete id="deleteAll" parameterType="list">
    delete from resources where id in
    <foreach collection="list" item="id" open="(" close=")" separator=",">
        #{id}
    </foreach>
</delete>

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM