Bootstrap --- Bootstrap Table表格组件(分页)

bootstrap Table 的优势:
1、界面采用扁平化的风格,用户体验比较好,更好兼容各种客户端。
2、开源、免费。
3、相对Jqgrid、easyUI而言,比较轻量级。功能不能说最全面,但基本够用。

Bootstrap Table的引入

  • 下载源码,添加到项目中
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/css/bootstrap-table.min.css">
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/bootstrap-table.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/locales/bootstrap-table-zh-CN.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/userTable.js"></script>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户管理</title>

<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/css/bootstrap-table.min.css">
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/bootstrap-table.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/userTable.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/layer/1.9.3/layer.js"></script>
</head>
<body>

<!-- 导航辅助 开始 -->
<!-- 一级标签选中 -->
<input id="nav-flag-top" type="hidden" value="nav-flag-top-sys"/>
<!-- 二级标签选中 -->
<input id="nav-flag-sub" type="hidden" value="nav-flag-sub-sys-zd"/>
<!-- 导航辅助 结束 -->

<div class="row" style="margin: 0;">
    <div class="minheight">

        <div class="col-sm-12">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <div class="" style="height: 30px;">
                        <div class="filter">
                            <form action="">
                                <div class="form-group bs_date">
                                    <label class='control-label' style='font-weight: normal; float: left; padding-right: 10px;'>所属部门</label>
                                    <div class="">
                                        <select id="ssbm" class='form-control' name='ssWeibanju'>
                                            <option value="">请选择</option>
                                        </select>
                                    </div>
                                </div>
                                <div id="toolbuton" class="">
                                    <button id="btn_delete" type="button" class="" onclick="deleteUser();">删除</button>
                                    <button id="btn_edit" type="button" class=""
                                            onclick="ShowDiv('EditDiv','EditFade')">修改
                                    </button>
                                    <button id="btn_add" type="button" class="" onclick="ShowDiv('MyDiv','fade')">添加
                                    </button>
                                    <button type="button" onclick="refreshData()">查询</button>
                                </div>
                            </form>
                        </div>
                    </div>


                    <!-- 新增 -->
                    <div id="fade" class="black_overlay"></div>
                    <div id="MyDiv" class="white_content">
                        <div style="text-align: right; cursor: default;margin-bottom: 10px;">
                        <span style="font-size: 16px;" onclick="CloseDiv('MyDiv','fade')"><i
                                class="glyphicon glyphicon-remove"></i></span>
                        </div>
                        <form class='form-horizontal clearfix' id="addPostForm" method="post"
                              enctype="multipart/form-data">
                            <table class="table" style="height: 300px;text-align: left;">
                                <tr>
                                    <th height="34px;">权利编码</th>
                                    <th><input type="text" name="powerCode" class="form-control"
                                               aria-describedby="basic-addon1" placeholder="请输入权利编码">
                                    </th>
                                    <th height="34px;">所属部门</th>
                                    <th><input type="text" name="ssWeibanju" class="form-control"
                                               aria-describedby="basic-addon1" placeholder="请输入所属部门"></th>
                                </tr>
                                <tr>
                                    <th height="34px;">检查事项名称</th>
                                    <th><textarea name="powerDesc" class="form-control" aria-describedby="basic-addon1"
                                                  placeholder="请输入问责内容"></textarea>
                                    </th>
                                    <th>行驶阶层</th>
                                    <th><input type="text" name="execLevel" class="form-control"
                                               aria-describedby="basic-addon1" placeholder="请输入行驶阶层"></th>
                                </tr>
                                <tr>
                                    <th height="34px;">工作日时限</th>
                                    <th><input type="text" name="limitedWorkdays" class="form-control"
                                               aria-describedby="basic-addon1" placeholder="请输入工作日时限"/>
                                    </th>
                                    <th></th>
                                    <th>
                                    </th>
                                </tr>
                                <%-- <input type="hidden" name="" id="id"/>--%>

                            </table>
                            <div class="btn-group" role="group" aria-label="" style="margin-left: 40%;">
                                <button type="button" class="btn btn-default" onclick="addList();">确定</button>
                                <button type="button" class="btn btn-default" onclick="CloseDiv('MyDiv','fade')">取消
                                </button>
                            </div>
                        </form>
                    </div>

                    <!-- 编辑 -->
                    <div id="EditFade" class="black_overlay"></div>
                    <div id="EditDiv" class="white_content">
                        <div style="text-align: right; cursor: default;margin-bottom: 10px;">
                        <span style="font-size: 16px;" onclick="CloseDiv('EditDiv','EditFade')"><i
                                class="glyphicon glyphicon-remove"></i></span>
                        </div>
                        <form class='form-horizontal clearfix' id="editPostForm" method="post"
                              enctype="multipart/form-data">
                            <table class="table" style="height: 300px;text-align: left;">
                                <tr>
                                    <th height="34px;">权利编码</th>
                                    <th><input type="text" name="powerCode" class="form-control"
                                               aria-describedby="basic-addon1" placeholder="请输入权利编码">
                                    </th>
                                    <th>所属部门</th>
                                    <th><input type="text" name="ssWeibanju" class="form-control"
                                               aria-describedby="basic-addon1" placeholder="请输入所属部门"></th>
                                </tr>
                                <tr>
                                    <th height="34px;">检查事项名称</th>
                                    <th><textarea name="powerDesc" class="form-control" aria-describedby="basic-addon1"
                                                  placeholder="请输入问责内容"></textarea>
                                    </th>
                                    <th>行驶阶层</th>
                                    <th><input type="text" name="execLevel" class="form-control"
                                               aria-describedby="basic-addon1" placeholder="请输入行驶阶层"></th>
                                </tr>
                                <tr>
                                    <th height="34px;">工作日时限</th>
                                    <th><input type="text" name="limitedWorkdays" class="form-control"
                                               aria-describedby="basic-addon1" placeholder="请输入工作日时限"/>
                                    </th>
                                    <th></th>
                                    <th>
                                    </th>

                                </tr>
                                <input type="hidden" name="id" id="id"/>
                            </table>
                            <div class="btn-group" role="group" aria-label="" style="margin-left: 40%;">
                                <button type="button" class="btn btn-default" onclick="updateList();">确定</button>
                                <button type="button" class="btn btn-default" onclick="CloseDiv('EditDiv','EditFade')">
                                    取消
                                </button>
                            </div>
                        </form>
                    </div>

                    <%--<div id="toolbar" class="btn-group">
                        <button id="btn_add" type="button" class="btn btn-default" onclick="ShowDiv('MyDiv','fade')">
                            <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>添加
                        </button>
                        <button id="btn_edit" type="button" class="btn btn-default" onclick="ShowDiv('EditDiv','EditFade')">
                            <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
                        </button>
                        <button id="btn_delete" type="button" class="btn btn-default" onclick="deleteUser();">
                            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
                        </button>
                    </div>--%>
                    <table id="table">

                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    //弹出隐藏层
    function ShowDiv(show_div, bg_div) {

        if (show_div == "EditDiv") {
            var selectedRow = $('#table').bootstrapTable('getSelections', null);

            if (selectedRow == null || selectedRow.length == 0) {
                layer.msg("请选择要修改的记录");
                return false;
            }
            selectedRow = selectedRow[0];
            $("#EditDiv input[name='id']").val(selectedRow.id);
            $("#EditDiv input[name='powerCode']").val(selectedRow.powerCode);
            $("#EditDiv input[name='ssWeibanju']").val(selectedRow.ssWeibanju);
            $("#EditDiv textarea[name='powerDesc']").val(selectedRow.powerDesc);
            $("#EditDiv input[name='execLevel']").val(selectedRow.execLevel);
            $("#EditDiv input[name='limitedWorkdays']").val(selectedRow.limitedWorkdays);
        }
        document.getElementById(show_div).style.display = 'block';
        document.getElementById(bg_div).style.display = 'block';

        var bgdiv = document.getElementById(bg_div);
        bgdiv.style.width = document.body.scrollWidth;
    };

    //关闭弹出层
    function CloseDiv(show_div, bg_div) {
        document.getElementById(show_div).style.display = 'none';
        document.getElementById(bg_div).style.display = 'none';
    };
    $("#cancel").click(function () {
        $("#EditDiv").hide();
        $("#EditFade").hide();
    })

        $(document).ready(function(){
            $.ajax({
                url:'../../frame/selectSsWeibanju',
                async: false,
                success:function (results){
                    var objs = JSON.parse(results);
                    var datas = eval(objs.rows);
                    for(var b in datas){
                        $("#ssbm").append("<option value='"+datas[b].ssWeibanju+"'>"+datas[b].ssWeibanju+"</option>");
                    }
                }
            });
        });
</script>
</body>
</html>
  • JS 表格分页代码详解
var oTable = null;
var groupId = "";
$(function () {
    //1.初始化Table
    oTable = new TableInit();
    oTable.Init();

    //2.初始化Button的点击事件
    var oButtonInit = new ButtonInit();
    oButtonInit.Init();
});

var columns = [{
    checkbox: true
}, {
    field: 'id',
    title: '主键id',
    visible: false
}, {
    field: 'Code',
    title: '编码',
    /* visible:false*/
}, {
    field: 'partment',
    title: '部门',
    width: '90px',
}, {
    field: 'category',
    title: '类别',
}];

var TableInit = function () {
    var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
        $('#table').bootstrapTable({
            url: '../../frame/listAllPower', //请求后台的URL(*)
            method: 'post', //请求方式(*)
            /* toolbar: '#toolbuton', //工具按钮用哪个容器*/
            striped: true, //是否显示行间隔色
            cache: false, //是否使用缓存,默认为true,一般情况下需要设置这个属性(*)
            pagination: true, //是否显示分页(*)
            sortable: false, //是否启用排序
            sortOrder: "asc", //排序方式
            queryParams: oTableInit.queryParams,//传递参数(*)
            sidePagination: "server", //分页方式:client分页,server分页(*)
            contentType: "application/x-www-form-urlencoded",
            dataType: 'json',
            pageNumber: 1, //初始化加载第一页,默认第一页
            pageSize: 10, //每页的记录行数(*)
            pageList: [10, 25, 50, 100], //可供选择的每页的行数(*)
            search: false, //是否显示表格搜索,此搜索是客户端搜索,意义不大
            strictSearch: true,
            showColumns: false, //是否显示所有的列
            showRefresh: false, //是否显示刷新按钮
            minimumCountColumns: 2, //最少允许的列数
            clickToSelect: true, //是否启用点击选中行
            singleSelect: true,
            height: 500, //行高,如果未设置height属性,表格自动根据记录条数决定表格高度
            uniqueId: "ID", //每一行的唯一标识,一般为主键列
            showToggle: false, //是否显示详细视图和列表视图的切换按钮
            cardView: false, //是否显示详细视图
            detailView: false, //是否显示父子表
            columns: columns              
        });
    };

    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = { //这里的key和controller的变量名一致
            rows: params.limit, //页面大小
            page: params.offset / params.limit + 1,//页码
            queryParam: params.queryparam //查询的参数
        };
        return temp;
    };

    oTableInit.refresh = function () {
        $("#table").bootstrapTable('refresh', {
            url: '../../frame/listAll'
        });
    }
    return oTableInit;
};
var ButtonInit = function () {
    var oInit = new Object();
    var postdata = {};
    oInit.Init = function () {
        //初始化页面上面的按钮事件
    };

    return oInit;
};

function refreshData() {
    $("#table").bootstrapTable('refreshOptions', {
        columns: columns,
        url: '../../frame/listAll',
        pageNumber: 1, //再次查询的起始页从第1页开始显示
        queryParams: function (params) {
            return {
                rows: params.limit, //页面大小
                page: params.offset / params.limit + 1,
                queryparam: $('#param').val() //根据条件查询
            }
        }
    });
};

//添加
function addList() {
    var options = {
        success: addCallBack,
        dataType: 'json',
        url: '../../frame/addObject'
    };

    $("#addPostForm").ajaxForm(options);
    $('#addPostForm').submit();
};

function addCallBack(result, statusText) {
    if (result == 1) {
        showDialog('提示', '保存成功!', callBack);
        $("#addPostForm")[0].reset();
        oTable.refresh();
    } else {
        showDialog('提示', '保存失败!', callBack);
    }
    ;

    function callBack() {
        $(".modal").modal('hide');
        $("#MyDiv").hide();
        $("#fade").hide();
        // oTable.refresh();
        window.location.reload();
    }
}

//编辑
function updateList() {
    var options = {
        success: editCallBack,
        dataType: 'json',
        url: '../../frame/updateObject'
    };

    $("#editPostForm").ajaxForm(options);
    $('#editPostForm').submit();
};

function editCallBack(result, statusText) {
    if (result == 1) {
        showDialog('提示', '保存成功!', callBack);
        $("#editPostForm")[0].reset();
        oTable.refresh();
    } else {
        showDialog('提示', '保存失败!', callBack);
    }
    ;

    function callBack() {
        $(".modal").modal('hide');
        $("#EditDiv").hide();
        $("#EditFade").hide();
        $("#fade").hide();
        window.location.reload();
    }
}

//删除
function deleteObject() {
    var selectedRow = $('#table').bootstrapTable('getSelections', null);

    if (selectedRow == null || selectedRow.length == 0) {
        alert("请选择要删除的记录");
        return false;
    }
    var flag = confirm("确认删除这条记录?");
    if (flag == true) {
        $.ajax({
            method: 'post',
            url: '../../frame/deleteObject',
            dataType: 'json',
            data: {
                id: selectedRow[0].id
            },
            success: function (result) {
                if (result > 0) {
                    alert("删除成功!");
                    oTable.refresh();
                } else {
                    alert("删除失败");
                    oTable.refresh();
                }
            }
        });
    }
}

注意:
如果是服务端分页,返回的结果必须包含totalrows两个参数。漏写或错写都会导致表 格无法显示数据。相反,如果是客户端分页,这里要返回一个集合对象到前端。

Mapper映射文件

<resultMap id="ListMap" type="com.java.model.Bean">
    <result property="id" column="id"/>
    <result property="code" column="code"/>
    <result property="department" column="department"/>
    <result property="deptCategory" column="dept_category"/>        
</resultMap>

<select id="selectByClause" resultMap="ListMap" parameterType="HashMap">
        select * from t_list
        <where>
            <if test="department!=null and department!= ''">
                and department= #{department}
            </if>
        </where>
        <if test="orderString !=null">
            order by id desc
        </if>
        <if test="page!=null and pageSize!=null">
            limit #{page},#{pageSize}
        </if>
</select>

<select id="selectCountByClause" resultType="java.lang.Integer" parameterType="HashMap">
    select count(*) from t_list
    <where>
        <if test="department !=null and department != ''">
            and department = #{department}
        </if>
    </where>
</select>

Service 查询分页

public List<Bean> selectByClause(String page, String rows, String department) {
        if (rows == null || "".equals(rows)) {
            rows = "10";
        }
        if (page == null || "".equals(page)) {
            page = "1";
        } else {
            int p = Integer.parseInt(page);
            int r = Integer.parseInt(rows);
            int pr = (p - 1) * r + 1;
            page = String.valueOf(pr);
        }
        Map map = new HashMap<String, Object>();
        map.put("page", Integer.parseInt(page) - 1);
        map.put("pageSize", Integer.parseInt(rows));
        map.put("department", department);
        List<Bean> list = listMapper.selectByClause(map);
        return list;
    }

Controller 分页展示

@Transactional
@RequestMapping(value = "/frame/listAllPower")
@ResponseBody
public Map listAll(HttpServletResponse response, String page, String rows, String department) throws IOException {
    List<Bean> list = ListService.selectByClause(page, rows, department);
    Map map = new HashMap<String, Object>();
    map.put("department", department);
    int count = listMapper.selectCountByClause(map);
    JSONObject result = new JSONObject();
    JSONArray jsonArray = JSONArray.fromObject(list);
    result.put("total", count);
    result.put("rows", jsonArray);
    try {
        ResponseUtil.write(response, result);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

参考

Bootstrap中文网:http://www.bootcss.com/

Bootstrap Table API:http://bootstrap-table.wenzhixin.net.cn/zh-cn/documentation/

Bootstrap DatePicker:http://www.bootcss.com/p/bootstrap-datetimepicker/

猜你喜欢

转载自blog.csdn.net/hakey/article/details/79403461