bootstarp table 封装

本文介绍如何配置BootstrapTable插件并实现数据表格的基本操作,包括重写默认参数、实现分页、筛选、编辑及导入导出等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

common.client.js 客户端

/**
 * 重写bootstrapTable 的默认参数
 * 减少每页的配置  服务端配置
 */
$.extend($.fn.bootstrapTable.defaults,{
    method:'post',
    search:false,
    //height : getHeight(),
    pagination : true, // 分页
    pageSize:30,//设置分页条数
    striped : true, // 是否显示行间隔色
    contentType: "application/x-www-form-urlencoded",
    //clickToSelect: true,//是否启用点击选中行
    //showToggle:true,//是否显示详细视图和列表视图的切换按钮
    cache : false, // 是否使用缓存
    pageList: [30, 50, 100],
    //showColumns : true, // 显示隐藏列
    //showRefresh : true, // 显示刷新按钮
    sidePagination : "client" // 客户端处理分页
});

common.server.js   服务端

/**
 * 重写bootstrapTable 的默认参数
 * 减少每页的配置  服务端配置
 */
$.extend($.fn.bootstrapTable.defaults,{
    method:'post',
    search:false,
    height : getHeight(),
    pagination : true, // 分页
    pageSize:30,//设置分页条数
    striped : true, // 是否显示行间隔色
    contentType: "application/x-www-form-urlencoded",
    //clickToSelect: true,//是否启用点击选中行
    //showToggle:true,//是否显示详细视图和列表视图的切换按钮
    cache : false, // 是否使用缓存
    //pageList : [ 20,30, 50],
    pageList: [30, 50, 100],
    showColumns : true, // 显示隐藏列
    //showRefresh : true, // 显示刷新按钮
    sidePagination : "server" // 服务端处理分页
});

js代码

<script th:inline="javascript">
    var $table = $('#empUserList'),
        $query = $('#btn_query'),
        $reset = $('#btn_reset'),
        $remove = $('#btn_delete'),
        $add = $('#btn_add'),
        $import = $('#btn_import'),
        $export = $('#btn_export');
    $(function () {
        $(".select2").select2();
        $table.bootstrapTable({
            url: getRootPath() + '/a/user/getSysUserPageList',
            queryParams: queryParams,
            buttonsAlign: "right",  //按钮位置
            toolbar: "#toolbar",// 指定工具栏
            uniqueId: "id", // 每一行的唯一标识
            classes: "table-striped table-hover table-bordered",
            columns: [{
                checkbox: true
            },
                {title: '部门', field: 'depName', align: 'center', valign: 'middle', sortable: true},
                {title: '用户名', field: 'username', align: 'center', valign: 'middle', sortable: true},
                {title: '真实姓名', field: 'realName', align: 'center', valign: 'middle', sortable: true},
                {title: '手机号', field: 'phone', align: 'center', valign: 'middle', sortable: true},
                {
                    title: '是否启用', field: 'flag', align: 'center', valign: 'middle', sortable: true,
                    formatter: function (value, row, index) {
                        var str = "";
                        if (value) {
                            str = "<div class='switch switch-mini' data-on='primary' data-off='info' data-id='" + row.id + "'><input type='checkbox' /></div>";
                        } else {
                            str = "<div class='switch switch-mini' data-on='primary' data-off='info' data-id='" + row.id + "'><input type='checkbox' checked /></div>";
                        }
                        return str;
                    }
                },
                {
                    title: '操作', field: 'id', align: 'center', valign: 'middle',
                    formatter: function (value, row, index) {
                        return permissionButton.join('');
                    },
                    events: {
                        'click [data-type="edit"]': function (e, value, row) {
                            layer_show("用户修改", getRootPath() + "/a/user/sysUserUpdate?id=" + value, "800", "600");
                        },
                        'click [data-type="delete"]': function (e, value, row) {
                            if (value == [[${session.loginUser.id}]]) {
                                $.fn.modalAlert('不可以删除自己!', 'error');
                                return;
                            }
                            $.fn.modalConfirm('确定要删除所选数据?', function () {
                                $.ajax({
                                    url: getRootPath() + '/a/user/sysUserDelete',
                                    type: "Post",
                                    data: {id: value},
                                    dataType: "json",
                                    success: function (result) {
                                        if (result > 0) {
                                            $.fn.modalMsg("操作成功", "success");
                                        } else {
                                            $.fn.modalMsg("操作失败", "error");
                                        }
                                        $remove.prop('disabled', true);
                                        $table.bootstrapTable('refresh');  //从新加载数据
                                    }
                                });
                            });
                        }
                    }
                }],
            onLoadSuccess: function () {  //加载成功时执行
                //layer.msg("加载成功");
                //$('#empUserList').bootstrapTable("refresh");
                //默认最小
                $('.switch input').bootstrapSwitch({
                    size: "mini"
                });
            },
            onLoadError: function () {  //加载失败时执行
                layer.msg("加载数据失败", {time: 1500, icon: 2});
            }
        });
        // sometimes footer render error.
        setTimeout(function () {
            $table.bootstrapTable('resetView', {
                height: getHeight()
            });
        }, 300);
        $(window).resize(function () {
            $table.bootstrapTable('resetView', {
                height: getHeight()
            });
        });
        //点击行中的checkbox  和全选的checkbox事件
        $table.on('check.bs.table uncheck.bs.table ' +
            'check-all.bs.table uncheck-all.bs.table', function () {
            $remove.prop('disabled', !$table.bootstrapTable('getSelections').length);
            // save your data, here just save the current page
            selections = getIdSelections();
        });
        $query.click(function () {
            $table.bootstrapTable('refresh');  //从新加载数据
        });
        $reset.click(function () {
            $(".form-inline .form-control").val("");
            $table.bootstrapTable('refresh');  //从新加载数据
        });
        $add.click(function () {
            layer_show("用户添加", getRootPath() + "/a/user/sysUserAdd", "800", "600");
        });
        $import.click(function () {
            resetFileInput("filename");

            layer_showView("导入excel", "dialog", 400, 300);
        });

        $remove.click(function () {
            if (selections.length < 1) {
                $.fn.modalAlert('请选择一条或多条数据进行删除!', 'error');
            } else {
                //询问框
                $.fn.modalConfirm('确定要删除所选数据?', function () {
                    $.ajax({
                        url: getRootPath() + '/a/user/sysUserBatchDelete',
                        type: "Post",
                        data: {item: JSON.stringify(selections)},
                        dataType: "json",
                        success: function (result) {
                            if (result > 0) {
                                $.fn.modalMsg("操作成功", "success");
                            } else {
                                $.fn.modalMsg("操作失败", "error");
                            }
                            $remove.prop('disabled', true);
                            $table.bootstrapTable('refresh');  //从新加载数据
                        }
                    });
                });
            }
        });

        /* input 获取焦点 才能触发 刷新事件*/
        $("input").keydown(function () {
            if (event.keyCode == "13") {//keyCode=13是回车键
                if ($query.length > 0) {
                    $table.bootstrapTable('refresh');  //从新加载数据
                }
            }
        });
        $export.click(function () {
            window.open(getRootPath() + "/a/user/exportWord")
        });
        $table.on('switchChange.bootstrapSwitch', '.switch', function (event, state) {
            var id = $(this).attr('data-id');
            $.ajax({
                url: getRootPath() + '/a/user/updateUserByFlag',
                type: "Post",
                data: {id: id, flag: Number(!state)},
                dataType: "json",
                success: function (result) {
                    if (result > 0) {
                        $.fn.modalMsg("操作成功", "success");
                    } else {
                        $.fn.modalMsg("操作失败", "error");
                    }
                    //$table.bootstrapTable('refresh');    //从新加载数据
                }
            });
        });
        //导入 excel
        $("#imp_excel").click(function () {
            var formData = new FormData($('#form_table')[0]);
            $.ajax({
                type: 'post',
                url: getRootPath() + "/a/user/importExcel",
                data: formData,
                cache: false,
                processData: false,
                contentType: false
            }).success(function (data) {
                console.log(data);
            })
        });

    });

    /**
     * 返回所有的checked选中的值
     */
    function getIdSelections() {
        return $.map($table.bootstrapTable('getSelections'), function (row) {
            return row.id
        });
    }


    /**
     * 查询条件与分页数据
     * @param params
     * @returns {{limit: (*|number), offset, sort, order}}
     */
    function queryParams(params) {
        var temp = {   //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的
            limit: params.limit,   //页面大小
            offset: params.offset, //页码
            sort: params.sort,  //排序列名
            order: params.order //排序方式
            //search: params.search   //搜索框参数
        };
        getSearchFormData($("#searchForm"), temp);
        //console.log(temp);
        return temp;
    }
</script>
<div id="dialog" style="display: none">
    <form class="form-horizontal" id="form_table" enctype="multipart/form-data">
        <div class="col-md-12">
            <div class="form-group">
                <label class="col-sm-2 control-label">文件</label>
                <div class="col-sm-10">
                    <input class="form-input" type="file" name="filename" id="filename"
                           accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"/>
                </div>
            </div>

            <div class="form-group">
                <label class="col-sm-2 control-label"></label>
                <div class="col-sm-10">
                    <button class="btn btn-primary" id="imp_excel" type="button"><i class="fa fa-save"></i>&nbsp;开始导入
                    </button>
                    <button type="button" class="btn btn-danger" onclick="layer_closeView();"><i
                            class="fa fa-close"></i>&nbsp;关闭
                    </button>
                </div>
            </div>
        </div>
    </form>
</div>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值