利用bootstarp-table实现ajax分页表格

TP5分页很好用,但是样式比较简陋,最近发现了bootstarp-table用来做ajax分页表格挺好的,在这里把方法Mark一下。

首先引入插件,这里不多说,然后就是html页面了,在HTML只需要简单的定义出一个table就即可

//表单
<form id="form_2" class="p-20">
    <div class="row">
        <div class="col-8">
            <div class="form-group" style="display: flex">
                <select class="form-control input-group-addon col-2" name="type" style="border-bottom-right-radius: 0px; border-top-right-radius: 0px">
                    <option value="dm">订单号</option>
                    <option value="no">渠道流水号</option>
                </select>
                <input type="text" class="form-control col-6" name="num" style="border-bottom-left-radius: 0px; border-top-left-radius: 0px">
            </div>
        </div>
        <div class="col-12">
            <div class="form-group col-1" style="padding: 0px">
                <input type="submit" name="submit" class="btn btn-info" value="查询" />
            </div>
        </div>
    </div>
</form>
//表格
<table id="bootstrap_table"></table>

接着就可以在JS端初始化table了 

var TableInit = function () {
        var oTableInit = new Object();
        //初始化Table
        oTableInit.Init = function () {
            $('#bootstrap_table').bootstrapTable({
                url: "<?=url('getData')?>",         //请求后台的URL(*)
                method: 'get',                      //请求方式(*)
                toolbar: '#toolbar',                //工具按钮用哪个容器
                striped: false,                      //是否显示行间隔色
                cache: false,                       //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*)
                pagination: true,                   //是否显示分页(*)
                sortable: false,                     //是否启用排序
                sortOrder: "asc",                   //排序方式
                queryParams: oTableInit.queryParams,//传递参数(*)
                pagination: true,                   //表格底部显示分页条
                sidePagination: "server",           //分页方式:client客户端分页,server服务端分页(*)
                pageNumber: 1,                       //初始化加载第一页,默认第一页
                pageSize: 15,                       //每页的记录行数(*)
                pageList: [10, 25, 50, 100],        //可供选择的每页的行数(*)
                search: true,                       //是否显示表格搜索,此搜索是客户端搜索,不会进服务端,所以,个人感觉意义不大
                contentType: "application/x-www-form-urlencoded",
                strictSearch: true,
                showColumns: true,                  //是否显示内容下拉框
                showRefresh: true,                  //是否显示刷新按钮
                minimumCountColumns: 2,             //当列数小于此值时,将隐藏内容列下拉框。
                clickToSelect: true,                //是否启用点击选中行
                height: 730,                        //行高,如果没有设置height属性,表格自动根据记录条数觉得表格高度
                uniqueId: "id",                     //每一行的唯一标识,一般为主键列
                showToggle: false,                    //是否显示详细视图和列表视图的切换按钮
                cardView: false,                    //是否显示详细视图
                detailView: false,                   //是否显示父子表
                columns: [
                    {
                        field: 'id',
                        title: '订单号'
                    },
                    {
                        field: 'dt',
                        title: '交易时间'
                    },
                    {
                        field: 'money',
                        title: '金额'
                    },
                    {
                        field: 'status',
                        title: '交易状态'
                    },
                    {
                        field: 'pay_type',
                        title: '支付渠道'
                    },
                    {
                        field: 'device',
                        title: '终端号'
                    },
                    {
                        field: 'operator',
                        title: '收银员'
                    },
                    {
                        field: 'operate',
                        title: '操作',
                        formatter: operateFormatter //自定义方法,添加操作按钮
                    },
                ],
            });
        };

        return oTableInit;
    };
    function operateFormatter(value, row, index) {//赋予的参数
        return [
            '<a href="#">查看</a>',
        ].join('');
    }
    //提交表单,初始化表格
    var validate_2 = jQuery("#form_2").validate({
        submitHandler: function (form) {
            //销毁上次的table,否则只能查询一次
            $("#bootstrap_table").bootstrapTable('destroy');
            //初始化Table
            var oTable = new TableInit();
            //得到查询的参数
            oTable.queryParams = function (params) {
                //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的
                var  temp = $('#form_2').serialize()+'&limit='+params.limit+'&offset='+params.offset;
                return temp;
            };
            oTable.Init();
        }
    });

现在前端的工作已经完成,剩下的只要写完服务器端逻辑即可(如果选择服务器端分页,服务器给前端传值时格式必须为{'total': '1000', 'rows': '[......]'})

 /**
     * 获取table数据
     * @return \think\response\Json
     */
    public function getData()
    {
        $limit = input('limit');
        $offset = input('offset');
        $cid = input('client_id');
        $stime = input('stime');
        $etime = input('etime');
        $type = input('type');  //=dm时按订单号查询,=no时按流水号查询
        $where = [];
        if ($type) {
            if ($type == 'dm') {
                $where['id'] = input('num');
            } else {
                $where['no'] = input('num');
            }
            $total = $this->dmModel->where($where)->count();
            $rel = $this->dmModel->where($where)->select();
        } else {
            $where['dt'] = ['between', "{$stime},{$etime}"];
            if ($cid != 24) {
                $where['client_id'] = $cid;
                $ids = $this->dmMerchantRelation->get_merchant_ids($cid);
                if ($ids) {
                    $where['client_id'] = ['in', $ids];
                }
            }
            $total = $this->dmModel->where($where)->count();
            //当偏移值大于总数的一半时,换个方向查询
            if ($offset > ceil($total / 2)) {
                $offset = $total - $offset;
                $rel = $this->dmModel->where($where)->limit("{$limit},{$offset}")->select();
            } else {
                $rel = $this->dmModel->where($where)->limit("{$limit},{$offset}")->order('id desc')->select();
            }
        }
        //整理数据
        $row = $this->sortData($rel);
        $ret = ['total' => $total, 'rows' => $row];

        return json($ret);
    }

    /**
     * 整理数据
     * @param $info
     * @return array
     */
    protected function sortData($info)
    {
        $args = [];
        foreach ($info as $k => $item) {
            $args[$k]['id'] = $item['id'];
            $args[$k]['dt'] = $item['dt'];
            $args[$k]['money'] = $this->getTotal($item['total'], $item['refund_total']);
            $args[$k]['status'] = $this->getStatus($item['refund_total']);
            $args[$k]['pay_type'] = get_pay_type($item['pay']) ? get_pay_type($item['pay']) : '未知渠道';
            $args[$k]['device'] = "[{$item['device_id']}]" . get_device_name($item['device_id']);
            $args[$k]['operator'] = 'xxx';
        }
        return $args;
    }


书山有路勤为径 学海无涯苦作舟