BootstrapTable简单的使用

Bootstrap table是一款基于 Bootstrap 的 jQuery 表格插件,通过简单的设置,就可以拥有强大的单选、多选、排序、分页,以及编辑、导出、过滤(扩展)等等的功能。
本篇文章介绍bootstrap-table的简单的使用(查询,新增,修改,删除),在看之前,需要有一点点bootstrap的基础知识,很多bootstrap的相关知识点就不介绍了,只讲bootstrap-table的相关内容。

引入相关文件

bootstrap-table 的使用非常简单,只需要像引用JQuery一样将js文件以及css文件引入到html文档中即可,为了更快的访问js文件,可以访问cdn,这里将cdn链接放上,如果没有链接至互联网,请将文件下载到本地,在引入至项目中,下面是引用的文件,文件存放在了cdn节点

    <script src="https://cdn.staticfile.org/jquery/2.1.0/jquery.min.js"></script>/<!--JQuery-->
    <script src="http://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script><!--bootstrap-->
    <script src="http://cdn.staticfile.org/bootstrap-table/1.9.0/bootstrap-table.min.js"></script><!--bootstrap-table-->
    <script src="http://cdn.staticfile.org/bootstrap-table/1.9.0/locale/bootstrap-table-zh-CN.min.js"></script><!--汉化文件-->

可以看到引入的文件有JQuery,由于bootstrap是基于JQuery 的一个框架,引入Bootstrap文件之前需要引入JQuery,而bootstrap-table是基于bootstrap的,所以必须引入JQuery;下面是Bootstrap框架的js,继续往下是bootstrap-table的js文件,最下面是汉化的js文件。引入js文件之后,为了美观还需要引入css(外部样式表)文件,也是bootstrap框架的文件,如果不引入,没有样式,界面很不美观;下面是需要引入的bootstrap的css文件和bootstrap-table需要用到的css文件。

    <link rel="stylesheet" href="http://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="http://cdn.staticfile.org/bootstrap-table/1.9.0/bootstrap-table.min.css">

简单的使用

首先,我把这个案例的全部html代码和css代码放上去,然后一点一点拆解

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <title>学生信息</title>
    <link rel="stylesheet" href="http://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="http://cdn.staticfile.org/bootstrap-table/1.9.0/bootstrap-table.min.css">
<!--    <link rel="stylesheet" href="/css/style.min862f.css">-->
    <script src="https://cdn.staticfile.org/jquery/2.1.0/jquery.min.js"></script><!---->
    <script src="http://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="http://cdn.staticfile.org/bootstrap-table/1.9.0/bootstrap-table.min.js"></script>
    <script src="http://cdn.staticfile.org/bootstrap-table/1.9.0/locale/bootstrap-table-zh-CN.min.js"></script>
</head>
<body>
<nav class="navbar navbar-default">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                    data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">Brand</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <form class="navbar-form navbar-left" id="searchForm">
                <div class="form-group">
                    <input type="text" class="form-control" id="searStr" name="searStr" placeholder="Search">
                </div>
                <button type="submit" class="btn btn-default">搜索</button>
                <button type="button" class="btn btn-default" onclick="(function(){$('#stuDetailModal').modal('show')})()">新增</button>
            </form>
        </div><!-- /.navbar-collapse -->
    </div><!-- /.container-fluid -->
</nav>
<div class="container">
    <div class="row">
        <table id="table"></table>
    </div>
</div>

<div class="modal fade" tabindex="-1" role="dialog" id="stuDetailModal">
    <div class="modal-dialog" role="document" style="width: 70%">
        <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">
                <input type="hidden" name="stuIndex" id="stuIndex">
                <div class="form-horizontal">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">学号</label>
                        <div class="col-sm-3">
                            <input type="text" class="form-control" id="stuId" name="stuId" value="" disabled="disabled" readonly="readonly"/>
                        </div>

                        <label class="col-sm-2 control-label">姓名</label>
                        <div class="col-sm-3">
                            <input type="text" class="form-control" id="stuName" name="stuName" value="" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">性别</label>
                        <div class="col-sm-3">
                            <input type="text" class="form-control" id="stuGender" name="stuGender" value="" />
                        </div>
                        <label class="col-sm-2 control-label">年龄</label>
                        <div class="col-sm-3">
                            <input type="text" class="form-control" id="stuAge" name="stuAge" value="" />
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">电话</label>
                        <div class="col-sm-3">
                            <input type="text" class="form-control" id="stuPhone" name="stuPhone" value="" />
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-sm btn-primary" onclick="saveStudentInfo()">保存</button>
                <button type="button" class="btn btn-sm btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script type="text/javascript">
    function queryParams(params) {
        return {type: "owner", direction: "desc", limit: params.limit, offset: params.offset}
    }
    $(function(){
        searchMusicList();
    })
    function showStudentInfoDetailModal(rid) {
        $('#stuDetailModal').modal('show');
        $.get("/students3/getStudentByStuId",{stuId:rid}, function (res) {
            res = JSON.parse(res);
            if (res.result == 'success'){
                if (res != null) {
                    $("#stuId").val(res.StudentInfo.stu_id);
                    $("#stuName").val(res.StudentInfo.stu_name);
                    $("#stuGender").val(res.StudentInfo.stu_gender);
                    $("#stuPhone").val(res.StudentInfo.stu_phone);
                    $("#stuAge").val(res.StudentInfo.stu_age);
                }else {
                    alert('没有找到学生信息');
                }
            }else if (res.result == 'fail'){
                alert('获取学生信息失败!');
            }else{
                alert(res.result);
            }
        })
    }

    function searchMusicList() {
        $('#table').bootstrapTable('destroy');
        $('#table').bootstrapTable({
            url: "/students3/getAllStudent",
            height:500,
            dataType: "json",
            pagination: true,
            pageSize: 30,
            queryParams:queryParams,
            sortable:true,
            sidePagination: "server",
            pageList: [30, 50],
            columns: [{
                title: '序号',
                width: "5%",
                field: 'rowNo',
            }, {
                field: 'stu_id',
                title: '学号',
                width: "10%",
                sortable:true
            }, {
                field: 'stu_name',
                title: '姓名',
                width: "10%",
                sortable:true
            }, {
                field: 'stu_age',
                title: '年龄',
                width: "10%",
                sortable:true
            }, {
                field: 'stu_gender',
                sortable:true,
                title: '性别',
                width: "10%", formatter: function (value, row, index) {
                    if (value == 'M') return '男';
                    else if (value == 'F') return '女';
                    else return value;
                }
            }, {
                field: 'stu_phone',
                title: '联系方式',
                width: "10%",
            }, {
                title: '操作',
                class: 'text-center',
                width: '20%',
                formatter: function (value, row, index) {
                    let res = "<button class='btn btn-sm btn-info' οnclick='showStudentInfoDetailModal(" + row.stu_id + ")' >详情</button>&nbsp;";
                    res += "<button class='btn btn-sm btn-primary' οnclick='modifyStudentInfoDetailModal(" +index + ")'>修改</button>&nbsp;";
                    res += "<button class='btn btn-sm btn-danger' οnclick='removeStudentBuId(" +index + ")'>删除</button>";
                    return res;
                }
            },],onPostBody: function (value) {
                // 解决模态框加载table数据的时候,底部数据超出表格的问题
                $(".fixed-table-container").css('padding-bottom', '37px');
            }
        });
        return false;
    }

    $("#searchForm").submit(function (e) {
        let option = $('#table').bootstrapTable('getOptions');
        option.queryParams = function(params){
            let searStr = document.getElementById('searStr').value;
            params.stuname = searStr;
            return params;
        }
        $('#table').bootstrapTable('refresh',option);
        return false;
    })

    function modifyStudentInfoDetailModal(i){
        const stuInfo = $('#table').bootstrapTable('getData')[i];
        $("#stuId").val(stuInfo.stu_id);
        $("#stuName").val(stuInfo.stu_name);
        $("#stuGender").val(stuInfo.stu_gender);
        $("#stuPhone").val(stuInfo.stu_phone);
        $("#stuAge").val(stuInfo.stu_age);
        $("#stuIndex").val(i);
        $('#stuDetailModal').modal('show');
    }
    function  saveStudentInfo(){
        const stuId = $("#stuId").val();
        const stuName = $("#stuName").val();
        const stuGender = $("#stuGender").val();
        const stuPhone = $("#stuPhone").val();
        const stuAge = $("#stuAge").val();
        const stuIndex = $("#stuIndex").val();
        const student = {stu_id: stuId, stu_name: stuName, stu_gender: stuGender, stu_phone: stuPhone, stu_age: stuAge};
        $.post("/students3/saveStudentInfo" ,student, function (res) {
           res = JSON.parse(res);
           if (res.result == 'success' ){
               if (res.flag == true){
                   $('#stuDetailModal').modal('hide');
                   alert("更新成功!");
                   if(stuId == '' || stuId == null){
                   		student.stu_id = res.stuId;
                       $('#table').bootstrapTable('prepend', student);
                   } else {
                       $("#table").bootstrapTable("updateRow", {
                           index:stuIndex,//更新行索引,0起始
                           replace:false,//合并or替换行数据,true替换,false合并,默认false
                           row:student
                       });
                   }
               }else{
                   alert('学生信息更新失败,请检查!');
                   $('#stuDetailModal').modal('hide');
               }
           }else if (res.result == 'fail' ){
               alert('学生信息更新失败');
           }else{
               alert(res.result);
           }
        })
    }
    function removeStudentBuId(i){
        const stuInfo = $('#table').bootstrapTable('getData')[i];
        let flag = confirm(`确定要删除姓名为: ${stuInfo.stu_name} 学号为: ${stuInfo.stu_id} 的学生吗?`);
        if (!flag) return false;
        $.post("/students3/removeStudentBuId" , stuInfo, function (res) {
            res = JSON.parse(res);
            if (res.result == 'success' ){
                if (res.flag == true){
                    $("#table").bootstrapTable('remove', {field:'stu_id',values:[stuInfo.stu_id]});
                    alert("删除成功!");
                }else{
                    alert('学生信息删除失败,请检查!');
                    $('#stuDetailModal').modal('hide');
                }
            }else if (res.result == 'fail' ){
                alert('学生信息删除失败');
            }else{
                alert(res.result);
            }
        })
    }
    $('#stuDetailModal').on('hidden.bs.modal', function () {//学生信息模态框关闭,清空缓存
        $("#stuId").val('');
        $("#stuName").val('');
        $("#stuGender").val('');
        $("#stuPhone").val('');
        $("#stuAge").val('');
        $("#stuIndex").val('');
    })
</script>
</body>
</html>


bootstrap-table的初始化

首先,bootstrap-table渲染数据使用的是table标签,需要创建一个table标签用来渲染等会即将出现的内容,只需要一个table标签然后配置一下相关参数bootstrap-table会帮我们渲染出相对应的界面,生成相关标签。下面是用来等会渲染数据的table,id为table,外层div的container类是bootstrap的样式,为了拉开两边的距离。row的类是定义了这是一行,这样,row会被撑开,不至于布局错乱。

<div class="container">
    <div class="row">
        <table id="table"></table>
    </div>
</div>

接下来看bootstrap-table的js代码

function queryParams(params) {
        return {type: "owner", direction: "desc", limit: params.limit, offset: params.offset}
    }
function searchMusicList() {
        $('#table').bootstrapTable('destroy');
        $('#table').bootstrapTable({
            url: "/students3/getAllStudent",
            height:500,
            dataType: "json",
            pagination: true,
            pageSize: 30,
            queryParams:queryParams,
            sortable:true,
            sidePagination: "server",
            pageList: [30, 50],
            columns: [{
                title: '序号',
                width: "5%",
                field: 'rowNo',
            }, {
                field: 'stu_id',
                title: '学号',
                width: "10%",
                sortable:true
            }, {
                field: 'stu_name',
                title: '姓名',
                width: "10%",
                sortable:true
            }, {
                field: 'stu_age',
                title: '年龄',
                width: "10%",
                sortable:true
            }, {
                field: 'stu_gender',
                sortable:true,
                title: '性别',
                width: "10%", formatter: function (value, row, index) {
                    if (value == 'M') return '男';
                    else if (value == 'F') return '女';
                    else return value;
                }
            }, {
                field: 'stu_phone',
                title: '联系方式',
                width: "10%",
            }, {
                title: '操作',
                class: 'text-center',
                width: '20%',
                formatter: function (value, row, index) {
                    let res = "<button class='btn btn-sm btn-info' οnclick='showStudentInfoDetailModal(" + row.stu_id + ")' >详情</button>&nbsp;";
                    res += "<button class='btn btn-sm btn-primary' οnclick='modifyStudentInfoDetailModal(" +index + ")'>修改</button>&nbsp;";
                    res += "<button class='btn btn-sm btn-danger' οnclick='removeStudentBuId(" +index + ")'>删除</button>";
                    return res;
                }
            },],onPostBody: function (value) {
                // 解决模态框加载table数据的时候,底部数据超出表格的问题
                $(".fixed-table-container").css('padding-bottom', '37px');
            }
        });
        return false;
  }

渲染数据很简单,只需要配置这些就能够将数据渲染出来,更多的配置讲解这里也就不过多介绍了,文档写得比我要更清楚,这里主要讲简单的应用,一些简单的增删改查。bootstrap-table需要的数据格式如下

{
	"result": "success",
	"lastNum": 0,
	"total": 1031,
	"recordsFiltered": 1031,
	"rows": [{
		"rowNo": 1,
		"stu_id": 2,
		"stu_name": "张三",
		"stu_gender": "男",
		"stu_age": 11,
		"stu_phone": "15036810833"
	}, {
		"rowNo": 2,
		"stu_id": 3,
		"stu_name": "张五",
		"stu_gender": "男",
		"stu_age": 18,
		"stu_phone": "15036810833"
	}],
	"recordsTotal": 1031
}

这里过多的重复的数据删除了,不做过多展示,这里面的参数“total”是一共有多少条数据,“rows”是具体的数据,如果响应的数据不是这种,可以用bootstrap-table里面的“responseHandler”方法进行格式化,比如响应的数据是这样的

{
	"result": "success",
	"allCount": 1031,
	"data": [{
		"rowNo": 1,
		"stu_id": 2,
		"stu_name": "张三",
		"stu_gender": "男",
		"stu_age": 11,
		"stu_phone": "15036810833"
	}, {
		"rowNo": 2,
		"stu_id": 3,
		"stu_name": "张五",
		"stu_gender": "男",
		"stu_age": 18,
		"stu_phone": "15036810833"
	}],
}

这样的数据bootstrap-table是不能识别的,需要格式化成bootstrap-table能识别的数据格式,这时候就可以用“responseHandler”进行格式化,写法如下


        $('#table').bootstrapTable('destroy');
        $('#table').bootstrapTable({
            url: "/students3/getAllStudent",
            height:500,
            dataType: "json",
            pagination: true,
            pageSize: 30,
            queryParams:queryParams,
            sortable:true,
            responseHandler:function(res){
                return {
                    "total":res.allCount,
                    "rows":res.data
                }
            },
            sidePagination: "server",
            pageList: [30, 50],
            columns: [{
                title: '序号',
                width: "5%",
                field: 'rowNo',
            }, {
                field: 'stu_id',
                title: '学号',
                width: "10%",
                sortable:true
            }, {
                field: 'stu_name',
                title: '姓名',
                width: "10%",
                sortable:true
            }, {
                field: 'stu_age',
                title: '年龄',
                width: "10%",
                sortable:true
            }, {
                field: 'stu_gender',
                sortable:true,
                title: '性别',
                width: "10%", formatter: function (value, row, index) {
                    if (value == 'M') return '男';
                    else if (value == 'F') return '女';
                    else return value;
                }
            }, {
                field: 'stu_phone',
                title: '联系方式',
                width: "10%",
            }, {
            	field: 'stu_id',
                title: '操作',
                class: 'text-center',
                width: '20%',
                formatter: function (value, row, index) {
                    let res = "<button class='btn btn-sm btn-info' οnclick='showStudentInfoDetailModal(" + row.stu_id + ")' >详情</button>&nbsp;";
                    res += "<button class='btn btn-sm btn-primary' οnclick='modifyStudentInfoDetailModal(" +index + ")'>修改</button>&nbsp;";
                    res += "<button class='btn btn-sm btn-danger' οnclick='removeStudentBuId(" +index + ")'>删除</button>";
                    return res;
                }
            }]
        });
        return false;
    }

这样经过格式化,可以不用改变后台的响应数据格式也能渲染出来,说完数据怎么渲染下面说一下数据的查询,其实bootstrap-table帮我们存了一份虚拟的数据在里面,当我们需要的时候就可以拿出来,哪怕渲染的时候没有将他显示出来,也是可以拿到的,下面介绍一下怎么取出来。观察上面的代码可以看到在操作列是有表达式的,以及性别列也是有表达式的,就是bootstrap-table的columns属性,这是一个数组,数组里面是一个一个的对象,

{
            	field: 'stu_id',
                title: '操作',
                class: 'text-center',
                width: '20%',
                formatter: function (value, row, index) {
                    let res = "<button class='btn btn-sm btn-info' οnclick='showStudentInfoDetailModal(" + row.stu_id + ")' >详情</button>&nbsp;";
                    res += "<button class='btn btn-sm btn-primary' οnclick='modifyStudentInfoDetailModal(" +index + ")'>修改</button>&nbsp;";
                    res += "<button class='btn btn-sm btn-danger' οnclick='removeStudentBuId(" +index + ")'>删除</button>";
                    return res;
                }
            }

对象里面的“formatter”属性可以是一个方法,这个方法有三个形参,分别是“value”, “row”, “index”,第一个就是当前列"field"属性里面的值,第二个“row”是当前行的对象也就是前面讲到的后台渲染数据的时候“rows”里面的每一个数据

{
		"rowNo": 2,
		"stu_id": 3,
		"stu_name": "张五",
		"stu_gender": "男",
		"stu_age": 18,
		"stu_phone": "15036810833"
	}

通过row.就能进行访问,“index”是当前行的索引,比如第一行数据是 0 第二行数据是 1,可以看到我写的函数里面写了一些html代码,通过拼接的方式将数据渲染到html上,我写的html代码是三个按钮,一个查看,一个修改,一个删除,这里详情就不讲了,就是简单的查看。

查询,修改

下面直接讲修改,修改的方法如下(其实上面也有了,不过为了不上下翻代码就写在这吧)

   /**
     * 将学生信息渲染到对应表单里面
     * @param Number i 操作的索引
     */
    function modifyStudentInfoDetailModal(i){
        const stuInfo = $('#table').bootstrapTable('getData')[i];
        $("#stuId").val(stuInfo.stu_id);
        $("#stuName").val(stuInfo.stu_name);
        $("#stuGender").val(stuInfo.stu_gender);
        $("#stuPhone").val(stuInfo.stu_phone);
        $("#stuAge").val(stuInfo.stu_age);
        $("#stuIndex").val(i);//记录操作索引
        $('#stuDetailModal').modal('show');//打开模态框
    }
    function  saveStudentInfo(){
        const stuId = $("#stuId").val();
        const stuName = $("#stuName").val();
        const stuGender = $("#stuGender").val();
        const stuPhone = $("#stuPhone").val();
        const stuAge = $("#stuAge").val();
        const stuIndex = $("#stuIndex").val();
        const student = {stu_id: stuId, stu_name: stuName, stu_gender: stuGender, stu_phone: stuPhone, stu_age: stuAge};
        $.post("/students3/saveStudentInfo" ,student, function (res) {
           res = JSON.parse(res);
           if (res.result == 'success' ){
               if (res.flag == true){
                   $('#stuDetailModal').modal('hide');
                   alert("更新成功!");
                   if(stuId == '' || stuId == null){
                   		student.stu_id = res.stuId;
                       $('#table').bootstrapTable('prepend', student);
                   } else {
                       $("#table").bootstrapTable("updateRow", {
                           index:stuIndex,//更新行索引,0起始
                           replace:false,//合并or替换行数据,true替换,false合并,默认false
                           row:student
                       });
                   }
               }else{
                   alert('学生信息更新失败,请检查!');
                   $('#stuDetailModal').modal('hide');
               }
           }else if (res.result == 'fail' ){
               alert('学生信息更新失败');
           }else{
               alert(res.result);
           }
        })
    }

modifyStudentInfoDetailModal 这个方法是将数据渲染到页面上,形参i就是当前要操作数据的索引,这个是bootstrap-table需要用到的,取到对应的数据之后,渲染到html上,然后记录下当前操作的索引,获取数据方式很简单,使用 “bootstrapTable(‘getData’)”就能拿到,这个方法返回值是数组,然后根据索引取对应的数据就行了。接下来讲保存,保存其实就是搜集表单信息,然后讲数据发送到后台,然后等待响应结果,响应成功之后刷新表格或者将数据更新到bootstrap-table,这里我选择的是后者,相信大多数人和我一样,在编程的时候尽量减少服务器和客户端传输的数据量,比如这个更新学生信息的例子,如果直接调用$(‘#table’).bootstrapTable(‘refresh’)会更简单,但是这样会导致大量无用数据在网络中传输,因为我们要的就是一个修改的结果,数据也是前台传过去的,服务器也会响应一个结果,成功或者失败,所以直接拿当前结果更新到bootstrap-table中更好,而不是增加数据库的查询,增加前后台无用的交互。回到正题,这里保存很简单,搜集表格信息,找到操作的索引,然后调用bootstrap的"updateRow"方法将数据渲染到表格中。

删除

接下来讲一下删除,删除更简单了,方法如下

    function removeStudentBuId(i){
        const stuInfo = $('#table').bootstrapTable('getData')[i];
        let flag = confirm(`确定要删除姓名为: ${stuInfo.stu_name} 学号为: ${stuInfo.stu_id} 的学生吗?`);
        if (!flag) return false;
        $.post("/students3/removeStudentBuId" , stuInfo, function (res) {
            res = JSON.parse(res);
            if (res.result == 'success' ){
                if (res.flag == true){
                    $("#table").bootstrapTable('remove', {field:'stu_id',values:[stuInfo.stu_id]});
                    alert("删除成功!");
                }else{
                    alert('学生信息删除失败,请检查!');
                    $('#stuDetailModal').modal('hide');
                }
            }else if (res.result == 'fail' ){
                alert('学生信息删除失败');
            }else{
                alert(res.result);
            }
        })
    }

根据索引拿到要删除的数据,提示一下,这里我将整个student都传输到后台了,其实只要能识别是这个学生就行,不要把整个对象都传过去,然后更新bootstrap-table的时候调用bootstrap-table的remove方法就行了,需要的参数也是和服务器删除相似(其实服务器是假删除),只需要能标识出这个学生就行。

新增

点击搜索旁边的新增按钮,输入学生信息,和修改是一样的,这个判定是由后台进行判定,如果传过去的数据有学生id就是修改,否则为新增,模态框每次关闭都会清空相关信息,不用担心数据残留,这里的保存还是有bug的,比如序号没有更新,由于序号是后后台生成的,所以需要重新后台刷新数据,这里没有从后台取数据,所以序号是错的,但是可以通过前端写js进行修复,以后有时间再处理这个bug

总结

很简单的操作,主要讲bootstrap-table 的简单使用

JS组件Bootstrap Table使用方法详解 转载 2016年03月21日 15:06:09 标签: Bootstrap Table 最近客户提出需求,想将原有的管理系统,做下优化,通过手机也能很好展现,想到2个方案: a方案:保留原有的页面,新设计一套适合手机的页面,当手机访问时,进入m.zhy.com(手机页面),pc设备访问时,进入www.zhy.com(pc页面) b方案:采用bootstrap框架,替换原有页面,自动适应手机、平板、PC 设备 采用a方案,需要设计一套界面,并且要得重新写适合页面的接口,考虑到时间及成本问题,故项目采用了b方案 一、效果展示 二、BootStrap table简单介绍 bootStrap table 是一个轻量级的table插件,使用AJAX获取JSON格式的数据,其分页和数据填充很方便,支持国际化 三、使用方法 1、引入js、css [js] view plain copy <!--css样式--> <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet"> <link href="css/bootstrap/bootstrap-table.css" rel="stylesheet"> <!--js--> [removed][removed] [removed][removed] [removed][removed] [removed][removed] 2、table数据填充 bootStrap table获取数据有两种方式,一是通过table 的data-url属性指定数据源,二是通过JavaScript初始化表格时指定url来获取数据 [xhtml] view plain copy ... ... [xhtml] view plain copy $('#table').bootstrapTable({ url: 'data.json' }); 第二种方式交第一种而言在处理复杂数据时更为灵活,一般使用第二种方式来进行table数据填充。 [js] view plain copy $(function () { //1.初始化Table var oTable = new TableInit(); oTable.Init(); //2.初始化Button的点击事件 /* var oButtonInit = new ButtonInit(); oButtonInit.Init(); */ }); var TableInit = function () { var oTableInit = new Object(); //初始化Table oTableInit.Init = function () { $('#tradeList').bootstrapTable({ url: '/VenderManager/TradeList', //请求后台的URL(*) method: 'post', //请求方式(*) toolbar: '#toolbar', //工具按钮用哪个容器 striped: true, //是否显示行间隔色 cache: false, //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*) pagination: true, //是否显示分页(*) sortable: false, //是否启用排序 sortOrder: "asc", //排序方式 queryParams: oTableInit.queryParams,//传递参数(*) sidePagination: "server", //分页方式:client客户端分页,server服务端分页(*) pageNumber:1, //初始化加载第一页,默认第一页 pageSize: 50, //每页的记录行数(*) pageList: [10, 25, 50, 100], //可供选择的每页的行数(*) strictSearch: true, clickToSelect: true, //是否启用点击选中行 height: 460, //行高,如果没有设置height属性,表格自动根据记录条数觉得表格高度 uniqueId: "id", //每一行的唯一标识,一般为主键列 cardView: false, //是否显示详细视图 detailView: false, //是否显示父子表 columns: [{ field: 'id', title: '序号' }, { field: 'liushuiid', title: '交易编号' }, { field: 'orderid', title: '订单号' }, { field: 'receivetime', title: '交易时间' }, { field: 'price', title: '金额' }, { field: 'coin_credit', title: '投入硬币' }, { field: 'bill_credit', title: '投入纸币' }, { field: 'changes', title: '找零' }, { field: 'tradetype', title: '交易类型' },{ field: 'goodmachineid', title: '货机号' },{ field: 'inneridname', title: '货道号' },{ field: 'goodsName', title: '商品名称' }, { field: 'changestatus', title: '支付' },{ field: 'sendstatus', title: '出货' },] }); }; //得到查询的参数 oTableInit.queryParams = function (params) { var temp = { //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的 limit: params.limit, //页面大小 offset: params.offset, //页码 sdate: $("#stratTime").val(), edate: $("#endTime").val(), sellerid: $("#sellerid").val(), orderid: $("#orderid").val(), CardNumber: $("#CardNumber").val(), maxrows: params.limit, pageindex:params.pageNumber, portid: $("#portid").val(), CardNumber: $("#CardNumber").val(), tradetype:$('input:radio[name="tradetype"]:checked').val(), success:$('input:radio[name="success"]:checked').val(), }; return temp; }; return oTableInit; }; field字段必须与服务器端返回的字段对应才会显示出数据。 3、后台获取数据 a、servlet获取数据 [js] view plain copy BufferedReader bufr = new BufferedReader( new InputStreamReader(request.getInputStream(),"UTF-8")); StringBuilder sBuilder = new StringBuilder(""); String temp = ""; while((temp = bufr.readLine()) != null){ sBuilder.append(temp); } bufr.close(); String json = sBuilder.toString(); JSONObject json1 = JSONObject.fromObject(json); String sdate= json1.getString("sdate");//通过此方法获取前端数据 ... b、springMvc Controller里面对应的方法获取数据 [js] view plain copy public JsonResult GetDepartment(int limit, int offset, string orderId, string SellerId,PortId,CardNumber,Success,maxrows,tradetype) { ... } 4、分页(遇到问题最多的) 使用分页,server端返回的数据必须包括rows和total,代码如下: [js] view plain copy ...gblst = SqlADO.getTradeList(sql,pageindex,maxrows); JSONArray jsonData=new JSONArray(); JSONObject jo=null; for (int i=0,len=gblst.size();i<len;i++) { TradeBean tb = gblst.get(i); if(tb==null) { continue; } jo=new JSONObject(); jo.put("id", i+1); jo.put("liushuiid", tb.getLiushuiid()); jo.put("price", String.format("%1.2f",tb.getPrice()/100.0)); jo.put("mobilephone", tb.getMobilephone()); jo.put("receivetime", ToolBox.getYMDHMS(tb.getReceivetime())); jo.put("tradetype", clsConst.TRADE_TYPE_DES[tb.getTradetype()]); jo.put("changestatus", (tb.getChangestatus()!=0)?"成功":"失败"); jo.put("sendstatus", (tb.getSendstatus()!=0)?"成功":"失败"); jo.put("bill_credit", String.format("%1.2f",tb.getBill_credit()/100.0)); jo.put("changes",String.format("%1.2f",tb.getChanges()/100.0)); jo.put("goodroadid", tb.getGoodroadid()); jo.put("SmsContent", tb.getSmsContent()); jo.put("orderid", tb.getOrderid()); jo.put("goodsName", tb.getGoodsName()); jo.put("inneridname", tb.getInneridname()); jo.put("xmlstr", tb.getXmlstr()); jsonData.add(jo); } int TotalCount=SqlADO.getTradeRowsCount(sql); JSONObject jsonObject=new JSONObject(); jsonObject.put("rows", jsonData);//JSONArray jsonObject.put("total",TotalCount);//总记录数 out.print(jsonObject.toString()); ... 5、分页界面内容介绍 前端获取分页数据,代码如下: [js] view plain copy ...oTableInit.queryParams = function (params) { var temp = { //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的 limit: params.limit, //第几条记录 offset: params.offset, //显示一页多少记录 sdate: $("#stratTime").val(), }; return temp; };... 后端获取分页数据,代码如下: [js] view plain copy ...int pageindex=0; int offset = ToolBox.filterInt(json1.getString("offset")); int limit = ToolBox.filterInt(json1.getString("limit")); if(offset !=0){ pageindex = offset/limit; } pageindex+= 1;//第几页... 以上就是为大家分享的Bootstrap Table使用方法,希望对大家熟练掌握Bootstrap Table使用方法有所帮助。 转自:http://www.jb51.net/article/79033.htm
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FeiSir_PC

您的三联和鼓励是我创作的最大动

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值