zoukankan      html  css  js  c++  java
  • 尚筹网项目第四天 2020-04-04 09:49:55

    本笔记大多来源于尚硅谷【封捷老师讲的尚筹网项目】

    视频地址:

    尚硅谷尚筹网项目视频教程
    下载链接:https://pan.baidu.com/s/1WOLG7b4yHkQfSMu3fMsOBA
    提取码:s5gw

    目标:实现对角色的增、删、改、查【基于ajax{地址栏不变}】

    1、角色分页

    1.1目标

    将角色信息分页显示

    1.2思路

    1.3代码

     创建页面role-page.jsp

    <%--
      Created by IntelliJ IDEA.
      User: 25017
      Date: 2020/4/6
      Time: 13:46
      To change this template use File | Settings | File Templates.
    --%>
    <%--
      Created by IntelliJ IDEA.
      User: 25017
      Date: 2020/3/23
      Time: 12:44
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    
    <!DOCTYPE html>
    <html lang="UTF-8">
    <%@include file="/WEB-INF/include-head.jsp" %>
    
    <body>
    
    <%@include file="/WEB-INF/include-nav.jsp" %>
    <div class="container-fluid">
        <div class="row">
            <%@include file="/WEB-INF/include-sidebar.jsp" %>
            <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title"><i class="glyphicon glyphicon-th"></i> 数据列表</h3>
                    </div>
                    <div class="panel-body">
                        <form class="form-inline" role="form" style="float:left;">
                            <div class="form-group has-feedback">
                                <div class="input-group">
                                    <div class="input-group-addon">查询条件</div>
                                    <input class="form-control has-success" type="text" placeholder="请输入查询条件">
                                </div>
                            </div>
                            <button type="button" class="btn btn-warning"><i class="glyphicon glyphicon-search"></i> 查询</button>
                        </form>
                        <button type="button" class="btn btn-danger" style="float:right;margin-left:10px;"><i class=" glyphicon glyphicon-remove"></i> 删除</button>
                        <button type="button" class="btn btn-primary" style="float:right;" onclick="window.location.href='form.html'"><i class="glyphicon glyphicon-plus"></i> 新增</button>
                        <br>
                        <hr style="clear:both;">
                        <div class="table-responsive">
                            <table class="table  table-bordered">
                                <thead>
                                <tr>
                                    <th width="30">#</th>
                                    <th width="30"><input type="checkbox"></th>
                                    <th>名称</th>
                                    <th width="100">操作</th>
                                </tr>
                                </thead>
                                <tbody>
                                <tr>
                                    <td>1</td>
                                    <td><input type="checkbox"></td>
                                    <td>PM - 项目经理</td>
                                    <td>
                                        <button type="button" class="btn btn-success btn-xs"><i class=" glyphicon glyphicon-check"></i></button>
                                        <button type="button" class="btn btn-primary btn-xs"><i class=" glyphicon glyphicon-pencil"></i></button>
                                        <button type="button" class="btn btn-danger btn-xs"><i class=" glyphicon glyphicon-remove"></i></button>
                                    </td>
                                </tr>
                                <tr>
                                    <td>2</td>
                                    <td><input type="checkbox"></td>
                                    <td>SE - 软件工程师</td>
                                    <td>
                                        <button type="button" class="btn btn-success btn-xs"><i class=" glyphicon glyphicon-check"></i></button>
                                        <button type="button" class="btn btn-primary btn-xs"><i class=" glyphicon glyphicon-pencil"></i></button>
                                        <button type="button" class="btn btn-danger btn-xs"><i class=" glyphicon glyphicon-remove"></i></button>
                                    </td>
                                </tr>
                                <tr>
                                    <td>3</td>
                                    <td><input type="checkbox"></td>
                                    <td>PG - 程序员</td>
                                    <td>
                                        <button type="button" class="btn btn-success btn-xs"><i class=" glyphicon glyphicon-check"></i></button>
                                        <button type="button" class="btn btn-primary btn-xs"><i class=" glyphicon glyphicon-pencil"></i></button>
                                        <button type="button" class="btn btn-danger btn-xs"><i class=" glyphicon glyphicon-remove"></i></button>
                                    </td>
                                </tr>
                                <tr>
                                    <td>4</td>
                                    <td><input type="checkbox"></td>
                                    <td>TL - 组长</td>
                                    <td>
                                        <button type="button" class="btn btn-success btn-xs"><i class=" glyphicon glyphicon-check"></i></button>
                                        <button type="button" class="btn btn-primary btn-xs"><i class=" glyphicon glyphicon-pencil"></i></button>
                                        <button type="button" class="btn btn-danger btn-xs"><i class=" glyphicon glyphicon-remove"></i></button>
                                    </td>
                                </tr>
                                <tr>
                                    <td>5</td>
                                    <td><input type="checkbox"></td>
                                    <td>GL - 组长</td>
                                    <td>
                                        <button type="button" class="btn btn-success btn-xs"><i class=" glyphicon glyphicon-check"></i></button>
                                        <button type="button" class="btn btn-primary btn-xs"><i class=" glyphicon glyphicon-pencil"></i></button>
                                        <button type="button" class="btn btn-danger btn-xs"><i class=" glyphicon glyphicon-remove"></i></button>
                                    </td>
                                </tr>
                                <tr>
                                    <td>6</td>
                                    <td><input type="checkbox"></td>
                                    <td>QA - 品质保证</td>
                                    <td>
                                        <button type="button" class="btn btn-success btn-xs"><i class=" glyphicon glyphicon-check"></i></button>
                                        <button type="button" class="btn btn-primary btn-xs"><i class=" glyphicon glyphicon-pencil"></i></button>
                                        <button type="button" class="btn btn-danger btn-xs"><i class=" glyphicon glyphicon-remove"></i></button>
                                    </td>
                                </tr>
                                <tr>
                                    <td>7</td>
                                    <td><input type="checkbox"></td>
                                    <td>QC - 品质控制</td>
                                    <td>
                                        <button type="button" class="btn btn-success btn-xs"><i class=" glyphicon glyphicon-check"></i></button>
                                        <button type="button" class="btn btn-primary btn-xs"><i class=" glyphicon glyphicon-pencil"></i></button>
                                        <button type="button" class="btn btn-danger btn-xs"><i class=" glyphicon glyphicon-remove"></i></button>
                                    </td>
                                </tr>
                                <tr>
                                    <td>8</td>
                                    <td><input type="checkbox"></td>
                                    <td>SA - 软件架构师</td>
                                    <td>
                                        <button type="button" class="btn btn-success btn-xs"><i class=" glyphicon glyphicon-check"></i></button>
                                        <button type="button" class="btn btn-primary btn-xs"><i class=" glyphicon glyphicon-pencil"></i></button>
                                        <button type="button" class="btn btn-danger btn-xs"><i class=" glyphicon glyphicon-remove"></i></button>
                                    </td>
                                </tr>
                                <tr>
                                    <td>8</td>
                                    <td><input type="checkbox"></td>
                                    <td>CMO / CMS - 配置管理员</td>
                                    <td>
                                        <button type="button" class="btn btn-success btn-xs"><i class=" glyphicon glyphicon-check"></i></button>
                                        <button type="button" class="btn btn-primary btn-xs"><i class=" glyphicon glyphicon-pencil"></i></button>
                                        <button type="button" class="btn btn-danger btn-xs"><i class=" glyphicon glyphicon-remove"></i></button>
                                    </td>
                                </tr>
                                </tbody>
                                <tfoot>
                                <tr>
                                    <td colspan="6" align="center">
                                        <ul class="pagination">
                                            <li class="disabled"><a href="#">上一页</a></li>
                                            <li class="active"><a href="#">1 <span class="sr-only">(current)</span></a></li>
                                            <li><a href="#">2</a></li>
                                            <li><a href="#">3</a></li>
                                            <li><a href="#">4</a></li>
                                            <li><a href="#">5</a></li>
                                            <li><a href="#">下一页</a></li>
                                        </ul>
                                    </td>
                                </tr>
    
                                </tfoot>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    </body>
    </html>

    由于去往角色页面不需要携带其他参数,直接使用view-controller跳转

    <mvc:view-controller path="/role/to/page.html" view-name="role-page"/>

    include-sidebar.jsp页面修改:

    <a href="role/to/page.html"><i class="glyphicon glyphicon-king"></i> 角色维护</a>

    后端代码【和查询管理员类似】:

    mapper.xml:

    <select id="selectRoleByKeyword" resultMap="BaseResultMap">
        select
          id, name
        from
        t_role
        where
        name like concat("%",#{keyword},"%")
      </select>

    接口:

    /**
         * 查询角色数据
         * @param keywords
         * @return
         */
        List<Role> selectRoleByKeyword(String keywords);

    service实现:

    package com.atguigu.crowd.service.impl;
    
    import com.atguigu.crowd.entity.Role;
    import com.atguigu.crowd.mapper.RoleMapper;
    import com.atguigu.crowd.service.api.RoleService;
    import com.github.pagehelper.PageHelper;
    import com.github.pagehelper.PageInfo;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    @Service
    public class RoleServiceImpl implements RoleService {
    
        @Autowired
        private RoleMapper roleMapper;
    
        /**
         * 查询角色的分页数据
         * @param pageNum 当前页号
         * @param pageSize 每页的条数
         * @param keyword 关键字模糊匹配
         * @return
         */
        @Override
        public PageInfo<Role> getPageInfo(Integer pageNum, Integer pageSize, String keyword) {
            // 开启分页
            PageHelper.startPage(pageNum,pageSize);
    
            // 执行查询
            List<Role> roles = roleMapper.selectRoleByKeyword(keyword);
    
            // 返回数据
            return new PageInfo<>(roles);
        }
    }

    handler:

    package com.atguigu.crowd.mvc.handler;
    
    import com.atguigu.crowd.entity.Role;
    import com.atguigu.crowd.service.api.RoleService;
    import com.atguigu.crowd.util.ResultEntity;
    import com.github.pagehelper.PageInfo;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @Controller
    public class RoleHandler {
    
        @Autowired
        private RoleService roleService;
    
        @ResponseBody
        @RequestMapping("/role/get/page/info.json")
        public ResultEntity<PageInfo<Role>> getPageInfo(
                @RequestParam(value="pageNum", defaultValue="1") Integer pageNum,
                @RequestParam(value="pageSize", defaultValue="5") Integer pageSize,
                @RequestParam(value="keyword", defaultValue="") String keyword) {
            // 调用 Service 方法获取分页数据
            PageInfo<Role> pageInfo = roleService.getPageInfo(pageNum, pageSize, keyword);
            // 封装到 ResultEntity 对象中返回(如果上面的操作抛出异常,交给异常映射机制处理)
            return ResultEntity.successWithData(pageInfo);
        }
    
    }

    页面:

    <link rel="stylesheet" href="css/pagination.css">
    <script type="text/javascript" src="jquery/jquery.pagination.js"></script>
    <script type="text/javascript" src="crowd/my-role.js"></script>

    外部my-role.js文件:

    /*
    本js文件是用于实现角色的分页
     */
    $(function(){
        // 1.为分页操作准备初始化数据
        window.pageNum = 1;
        window.pageSize = 5;
        window.keyword = "";
        // 2.调用执行分页的函数,显示分页效果
        generatePage();
    });
    
    // 执行分页,生成页面效果,任何时候调用这个函数都会重新加载页面
    function generatePage() {
        // 1.获取分页数据
        var pageInfo = getPageInfoRemote();
        // 2.填充表格
        fillTableBody(pageInfo);
    }
    
    // 远程访问服务器端程序获取 pageInfo 数据
    function getPageInfoRemote() {
        // 调用$.ajax()函数发送请求并接受$.ajax()函数的返回值
        var ajaxResult =
            $.ajax({
            "url": "role/get/page/info.json",
            "type":"post",
            "data": {
                "pageNum": window.pageNum,
                "pageSize": window.pageSize,
                "keyword": window.keyword
            },
            "async":false,
            "dataType":"json"
        });
        // console.log(ajaxResult);
        // 判断当前响应状态码是否为 200
        var statusCode = ajaxResult.status;
        // 如果当前响应状态码不是 200,说明发生了错误或其他意外情况,显示提示消息,让 当前函数停止执行
        if(statusCode != 200) {
            layer.msg("失败!响应状态码="+statusCode+" 说明信息="+ajaxResult.statusText);
            return null;
        }
        // 如果响应状态码是 200,说明请求处理成功,获取 pageInfo
        var resultEntity = ajaxResult.responseJSON;
        // 从 resultEntity 中获取 result 属性
        var result = resultEntity.result;
        // 判断 result 是否成功
        if(result == "FAILED") {
            layer.msg(resultEntity.message);
            return null;
        }
        // 确认 result 为成功后获取 pageInfo
        var pageInfo = resultEntity.data;
        // 返回 pageInfo
        return pageInfo;
    }
    
    // 填充表格
    function fillTableBody(pageInfo) {
        // 清除 tbody 中的旧的内容
        $("#rolePageBody").empty();
        // 这里清空是为了让没有搜索结果时不显示页码导航条
        $("#Pagination").empty();
        // 判断 pageInfo 对象是否有效
        if(pageInfo == null || pageInfo == undefined
            || pageInfo.list == null || pageInfo.list.length == 0) {
            $("#rolePageBody").append("<tr><td colspan='4' align='center'>抱歉!没有查询到您搜索的数据!</td></tr>");
            return ;
        }
        // 使用 pageInfo 的 list 属性填充 tbody
        for(var i = 0; i < pageInfo.list.length; i++) {
            var role = pageInfo.list[i];
            var roleId = role.id;
            var roleName = role.name;
            var numberTd = "<td>"+(i+1)+"</td>";
            var checkboxTd = "<td><input type='checkbox'></td>";
            var roleNameTd = "<td>"+roleName+"</td>";
            var checkBtn = "<button type='button' class='btn btn-success btn-xs'><i class=' glyphicon glyphicon-check'></i></button>";
            var pencilBtn = "<button type='button' class='btn btn-primary btn-xs'><i class=' glyphicon glyphicon-pencil'></i></button>";
            var removeBtn = "<button type='button' class='btn btn-danger btn-xs'><i class=' glyphicon glyphicon-remove'></i></button>";
            var buttonTd = "<td>"+checkBtn+" "+pencilBtn+" "+removeBtn+"</td>";
            var tr = "<tr>"+numberTd+checkboxTd+roleNameTd+buttonTd+"</tr>";
            $("#rolePageBody").append(tr);
        }
        // 生成分页导航条
        generateNavigator(pageInfo);
    }
    
    // 生成分页页码导航条
    function generateNavigator(pageInfo) {
        // 获取总记录数
        var totalRecord = pageInfo.total;
        // 声明相关属性
        var properties = {
            "num_edge_entries": 3,
            "num_display_entries": 5,
            "callback": paginationCallBack,
            "items_per_page": pageInfo.pageSize,
            "current_page": pageInfo.pageNum - 1,
            "prev_text": "上一页",
            "next_text": "下一页"
        }
        // 调用 pagination()函数
        $("#Pagination").pagination(totalRecord, properties);
    }
    
    // 翻页时的回调函数
    function paginationCallBack(pageIndex, jQuery) {
        // 修改 window 对象的 pageNum 属性
        window.pageNum = pageIndex + 1;
        // 调用分页函数
        generatePage();
        // 取消页码超链接的默认行为
        return false;
    }

    关键字查询:

    页面:

    <input id="keywordInput" class="form-control has-success" type="text" placeholder="请输入查询条件">
    
    <button id="searchBtn" type="button" class="btn btn-warning"><i class="glyphicon glyphicon-search"></i> 查询</button>

    js代码【注意:需要将其放入文档就绪函数中】:

    <script type="text/javascript">
    
        $(function(){
            // 关键字查询功能
            $("#searchBtn").click(function(){
                // ①获取关键词数据赋值给对应的全局变量
                window.keyword = $("#keywordInput").val();
           window.pageNum = 1;
    // ②调用分页函数刷新页面 generatePage(); }); }); </script>

    2、角色新增

    目标:

    通过在打开的模态框中输入角色名称,执行对新角色的保存。

    思路:

     代码:

    前端页面:

    role-add-modal.jsp

    <%--
      Created by IntelliJ IDEA.
      User: 25017
      Date: 2020/4/6
      Time: 22:52
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <div id="addModal" class="modal fade" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h4 class="modal-title">尚筹网系统弹窗</h4>
                </div>
                <div class="modal-body">
                    <form class="form-signin" role="form">
                        <div class="form-group has-success has-feedback">
                            <inputtype="text" name="roleName" class="form-control" id="inputSuccess4" placeholder="请输入 角色名称" autofocus>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button id="saveRoleBtn" type="button" class="btn btn-primary"> 保 存 </button>
                </div>
            </div>
        </div>
    </div>

    role-page页面修改:

    新增按钮添加id属性:
    <button id="showAddModalBtn" type="button" class="btn btn-primary" style="float:right;"><i class="glyphicon glyphicon-plus"></i> 新增</button>
    
    引入添加模态框:
    <%@include file="/WEB-INF/role-add-modal.jsp" %>

    js代码:

    // 4.点击新增按钮打开模态框
            $("#showAddModalBtn").click(function(){
                $("#addModal").modal("show");
            });
    
            // 5.给新增模态框中的保存按钮绑定单击响应函数
            $("#saveRoleBtn").click(function(){
                // ①获取用户在文本框中输入的角色名称
                // #addModal 表示找到整个模态框
                // 空格表示在后代元素中继续查找
                // [name=roleName]表示匹配 name 属性等于 roleName 的元素
                var roleName = $.trim($("#addModal [name=roleName]").val());
                // ②发送 Ajax 请求
                $.ajax({
                    "url": "role/save.json",
                    "type":"post",
                    "data": {
                        "name": roleName
                    },
                    "dataType": "json",
                    "success":function(response){
                        var result = response.result;
                        if(result == "SUCCESS") {
                            layer.msg("操作成功!");
                            // 将页码定位到最后一页
                            window.pageNum = 99999999;
                            window.keyword = roleName;
                            // 重新加载分页数据
                            generatePage();
                        }
                        if(result == "FAILED") {
                            layer.msg("操作失败!"+response.message);
                        }
                    },
                    "error":function(response){
                        layer.msg(response.status+" "+response.statusText);
                    }
                });
                // 关闭模态框
                $("#addModal").modal("hide");
                // 清理模态框
                $("#addModal [name=roleName]").val("");
            });

    后端代码:

    handler:

    @ResponseBody
        @RequestMapping("/role/save.json")
        public ResultEntity<String> saveRole(Role role) {
            roleService.saveRole(role);
            return ResultEntity.successWithoutData();
        }

    service实现:

    @Override
        public void saveRole(Role role) {
            roleMapper.insert(role);
        }

    3、角色更新

    目标:

    修改角色信息。

    思路:

    代码:

    页面:

    role-edit-modal.jsp

    <%--
      Created by IntelliJ IDEA.
      User: 25017
      Date: 2020/4/6
      Time: 22:52
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <div id="addModal" class="modal fade" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h4 class="modal-title">尚筹网系统弹窗</h4>
                </div>
                <div class="modal-body">
                    <form class="form-signin" role="form">
                        <div class="form-group has-success has-feedback">
                            <input type="text" name="roleName" class="form-control" id="inputSuccess4" placeholder="请输入 角色名称" autofocus>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button id="saveRoleBtn" type="button" class="btn btn-primary"> 保 存 </button>
                </div>
            </div>
        </div>
    </div>

    role-page修改:

    引入修改模态框
    <%@include file="/WEB-INF/role-edit-modal.jsp" %>

    my-role.js修改:

    原来:
    var pencilBtn = "<button type='button' class='btn btn-primary btn-xs'><i class=' glyphicon glyphicon-pencil'></i></button>";
    现在:
    // 通过 button 标签的 id 属性(别的属性其实也可以)把 roleId 值传递到 button 按钮的单击 响应函数中,
            // 在单击响应函数中使用 this.id
            var pencilBtn = "<button id='"+roleId+"' type='button' class='btn btn-primary btn-xs pencilBtn'><i class=' glyphicon glyphicon-pencil'></i></button>";

    js:

    // 6.给页面上的“铅笔”按钮绑定单击响应函数,目的是打开模态框
            // 传统的事件绑定方式只能在第一个页面有效,翻页后失效了
            // $(".pencilBtn").click(function(){
            //      alert("aaaa...");
            // });
            // 使用 jQuery 对象的 on()函数可以解决上面问题
            // ①首先找到所有“动态生成”的元素所附着的“静态”元素
            // ②on()函数的第一个参数是事件类型
            // ③on()函数的第二个参数是找到真正要绑定事件的元素的选择器
            // ③on()函数的第三个参数是事件的响应函数
            $("#rolePageBody").on("click",".pencilBtn",function(){
                // 打开模态框
                $("#editModal").modal("show");
                // 获取表格中当前行中的角色名称
                var roleName = $(this).parent().prev().text();
                // 获取当前角色的 id
                // 依据是:var pencilBtn = "<button id='"+roleId+"' ……这段代码中我们把 roleId 设置到 id 属性了
                // 为了让执行更新的按钮能够获取到 roleId 的值,把它放在全局变量上
                window.roleId = this.id;
                // 使用 roleName 的值设置模态框中的文本框
                $("#editModal [name=roleName]").val(roleName);
            });
    
            // 7.给更新模态框中的更新按钮绑定单击响应函数
            $("#updateRoleBtn").click(function(){
                // ①从文本框中获取新的角色名称
                var roleName = $("#editModal [name=roleName]").val();
                // ②发送 Ajax 请求执行更新
                $.ajax({
                    "url":"role/update.json",
                    "type":"post",
                    "data":{
                        "id":window.roleId,
                        "name":roleName
                    },
                    "dataType":"json",
                    "success":function(response){
                        var result = response.result;
                        if(result == "SUCCESS") {
                            layer.msg("操作成功!");
                            // 重新加载分页数据
                            generatePage();
                        }
                        if(result == "FAILED") {
                            layer.msg("操作失败!"+response.message);
                        }
                    },
                    "error":function(response){
                        layer.msg(response.status+" "+response.statusText);
                    }
                });
                // ③关闭模态框
                $("#editModal").modal("hide");
            });

    后端代码:

    handler:

    @ResponseBody
        @RequestMapping("/role/update.json")
        public ResultEntity<String> updateRole(Role role) {
            roleService.updateRole(role);
            return ResultEntity.successWithoutData();
        }

    service实现:

    @Override
        public void updateRole(Role role) {
            roleMapper.updateByPrimaryKey(role);
        }

    4、角色删除【包括批量删除和单条删除】

     目标:

    前端的“单条删除”和“批量删除”在后端合并为同一套操作。合并的依据是:单条删除时 id 也放在数组中,后端完全根据 id 的数组进行删除。

    思路:

    代码:

    页面:

    role-confirm-modal.jsp

    <%--
      Created by IntelliJ IDEA.
      User: 25017
      Date: 2020/4/6
      Time: 23:44
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    
    <div id="confirmModal" class="modal fade" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"
                            aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h4 class="modal-title">尚筹网系统弹窗</h4>
                </div>
                <div class="modal-body">
                    <h4>请确认是否要删除下列角色:</h4>
                    <div id="roleNameDiv" style="text-align: center;"></div>
                </div>
                <div class="modal-footer">
                    <button id="removeRoleBtn" type="button" class="btn btn-primary">确认删除</button>
                </div>
            </div>
        </div>
    </div>

    role-page:

    引入模态框:
    <%@include file="/WEB-INF/role-confirm-modal.jsp" %>
    删除按钮修改:
    <button id="batchRemoveBtn" type="button" class="btn btn-danger"
                                style="float: right; margin-left: 10px;">
                            <i class=" glyphicon glyphicon-remove"></i> 删除
                        </button>
    全选按钮修改:
    <th width="30">#</th>
                                    <th width="30"><input id="summaryBox" type="checkbox"></th>
                                    <th>名称</th>
                                    <th width="100">操作</th>

    my-role.js:

    多选时获取roleId:
    var checkboxTd = "<td><input class='itemBox' id='"+roleId+"' type='checkbox'></td>";
    单选时获取roleId
    var removeBtn = "<button id='"+roleId+"' type='button' class='btn btn-danger btn-xs removeBtn'><i class=' glyphicon glyphicon-remove'></i></button>";

    js:

    // 声明专门的函数显示确认模态框
    function showConfirmModal(roleArray) {
    
        // 打开模态框
        $("#confirmModal").modal("show");
    
        // 清除旧的数据
        $("#roleNameDiv").empty();
    
        // 在全局变量范围创建数组用来存放角色id
        window.roleIdArray = [];
    
        // 遍历roleArray数组
        for(var i = 0; i < roleArray.length; i++) {
            var role = roleArray[i];
            var roleName = role.roleName;
            $("#roleNameDiv").append(roleName+"<br/>");
    
            var roleId = role.roleId;
    
            // 调用数组对象的push()方法存入新元素
            window.roleIdArray.push(roleId);
        }
    
    }
    
    // 8.点击确认模态框中的确认删除按钮执行删除
            $("#removeRoleBtn").click(function(){
    
                // 从全局变量范围获取roleIdArray,转换为JSON字符串
                var requestBody = JSON.stringify(window.roleIdArray);
    
                $.ajax({
                    "url":"role/remove/by/role/id/array.json",
                    "type":"post",
                    "data":requestBody,
                    "contentType":"application/json;charset=UTF-8",
                    "dataType":"json",
                    "success":function(response){
    
                        var result = response.result;
    
                        if(result == "SUCCESS") {
                            layer.msg("操作成功!");
    
                            // 重新加载分页数据
                            generatePage();
                        }
    
                        if(result == "FAILED") {
                            layer.msg("操作失败!"+response.message);
                        }
    
                    },
                    "error":function(response){
                        layer.msg(response.status+" "+response.statusText);
                    }
                });
    
                // 关闭模态框
                $("#confirmModal").modal("hide");
    
            });
    
            // 9.给单条删除按钮绑定单击响应函数
            $("#rolePageBody").on("click",".removeBtn",function(){
    
                // 从当前按钮出发获取角色名称
                var roleName = $(this).parent().prev().text();
    
                // 创建role对象存入数组
                var roleArray = [{
                    "roleId":this.id,
                    "roleName":roleName
                }];
    
                // 调用专门的函数打开模态框
                showConfirmModal(roleArray);
    
            });
    
            // 10.给总的checkbox绑定单击响应函数
            $("#summaryBox").click(function(){
    
                // ①获取当前多选框自身的状态
                var currentStatus = this.checked;
    
                // ②用当前多选框的状态设置其他多选框
                $(".itemBox").prop("checked", currentStatus);
    
            });
    
            // 11.全选、全不选的反向操作
            $("#rolePageBody").on("click",".itemBox",function(){
    
                // 获取当前已经选中的.itemBox的数量
                var checkedBoxCount = $(".itemBox:checked").length;
    
                // 获取全部.itemBox的数量
                var totalBoxCount = $(".itemBox").length;
    
                // 使用二者的比较结果设置总的checkbox
                $("#summaryBox").prop("checked", checkedBoxCount == totalBoxCount);
    
            });
    
            // 12.给批量删除的按钮绑定单击响应函数
            $("#batchRemoveBtn").click(function(){
    
                // 创建一个数组对象用来存放后面获取到的角色对象
                var roleArray = [];
    
                // 遍历当前选中的多选框
                $(".itemBox:checked").each(function(){
    
                    // 使用this引用当前遍历得到的多选框
                    var roleId = this.id;
    
                    // 通过DOM操作获取角色名称
                    var roleName = $(this).parent().next().text();
    
                    roleArray.push({
                        "roleId":roleId,
                        "roleName":roleName
                    });
                });
    
                // 检查roleArray的长度是否为0
                if(roleArray.length == 0) {
                    layer.msg("请至少选择一个执行删除");
                    return ;
                }
    
                // 调用专门的函数打开模态框
                showConfirmModal(roleArray);
            });
    
    分页时将全选按钮默认不勾选:
    $("#summaryBox").prop("checked", false);

    后端:

    handler:

    @ResponseBody
        @RequestMapping("/role/remove/by/role/id/array.json")
        public ResultEntity<String> removeByRoleIdAarry(
                @RequestBody List<Integer> roleIdList) {
    
            roleService.removeRole(roleIdList);
    
            return ResultEntity.successWithoutData();
        }

    service实现:

    @Override
        public void removeRole(List<Integer> roleIdList) {
            RoleExample example = new RoleExample();
    
            RoleExample.Criteria criteria = example.createCriteria();
    
            //delete from t_role where id in (5,8,12)
            criteria.andIdIn(roleIdList);
    
            roleMapper.deleteByExample(example);
        }
  • 相关阅读:
    vue--父组件向子组件传参--父组件定义v-bind:参数名--子组件接收props----子组件调用父组件的方法(子组件向父组件传参)父组件@事件名称--子组件接收this.$emit
    vue--组件切换--带动画效果---component
    js string类型转换成数组对象类型---eval
    Vue--创建组件-template---定义私有组件
    vue--自定义标签属性--用于多个事件共同引用一个组件--但是两个事件要实现的功能不同-避免冲突
    vue--组件动画效果--淡入淡出--位移
    vue---向后台添加数据--删除数据--事件方法传参---在单页面配置url请求地址--暂时没有用到webpack
    vscode安装Bootstrap插件--方便补全代码段
    vue-resource--ajax请求数据
    生命周期演示--从加载--渲染--销毁
  • 原文地址:https://www.cnblogs.com/lxw-all/p/12632250.html
Copyright © 2011-2022 走看看