溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何用bootstrap table實現(xiàn)數(shù)據(jù)表格

發(fā)布時間:2020-07-09 10:06:31 來源:億速云 閱讀:508 作者:Leah 欄目:web開發(fā)

如何用bootstrap table實現(xiàn)數(shù)據(jù)表格?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

在使用bootstrap table時可能在很多時候回用的表格來顯示數(shù)據(jù),如果自己寫那肯定沒問題,但是數(shù)據(jù)展示出來就麻煩多了,然而bootstrap table 封裝了一套完善的數(shù)據(jù)表格組件,把從后臺請求的數(shù)據(jù)很容易就展示出來了,bootstrap table有兩種實現(xiàn)方式,一種是通過table寫定在html里面,另一種是通過js實現(xiàn),js實現(xiàn)比較靈活,所以這里采用js方式,下面來看實現(xiàn)。

如何用bootstrap table實現(xiàn)數(shù)據(jù)表格

客戶端

必須先引入相應的css、js等文件

 <!DOCTYPE html>
  <html>
  <head>
<meta charset="UTF-8">
<title>Bootstrap-Table</title>
<link rel="stylesheet" href="http://apps.bdimg.com/libs/bootstrap/3.3.4/css/bootstrap.min.css"/>
<link rel="stylesheet" href="assets/bootstrap-table.css"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
</head>
<body>
<div>
    <div>
        <div class="col-*-12">

            <div id="toolbar">
                <div class="btn btn-primary" data-toggle="modal" data-target="#addModal">添加記錄</div>
            </div>

            <table id="mytab" class="table table-hover"></table>

            <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-hidden="true">
               <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                                &times;
                            </button>
                            <h5 class="modal-title" id="myModalLabel">添加記錄</h5>
                        </div>
                        <div class="modal-body">
                            <form role="form" action="javascript:void(0)">
                                <div class="form-group">
                                    <input type="text" class="form-control" id="name" placeholder="請輸入名稱">
                                </div>
                                <div class="form-group">
                                    <input type="text" class="form-control" id="age" placeholder="請輸入年齡">
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                            <button type="button" class="btn btn-primary" id="addRecord">提交</button>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
</div>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="http://apps.bdimg.com/libs/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="assets/bootstrap-table.js"></script>
<script src="assets/bootstrap-table-zh-CN.js"></script>
<script type="text/javascript">
    $(function() {
        //根據(jù)窗口調(diào)整表格高度
        $(window).resize(function() {
            $('#mytab').bootstrapTable('resetView', {
                height: tableHeight()
            })
        })

        $('#mytab').bootstrapTable({
            url: "",//數(shù)據(jù)源
            dataField: "rows",//服務端返回數(shù)據(jù)鍵值 就是說記錄放的鍵值是rows,分頁時使用總記錄數(shù)的鍵值為total
            height: tableHeight(),//高度調(diào)整
            search: true,//是否搜索
            pagination: true,//是否分頁
            pageSize: 20,//單頁記錄數(shù)
            pageList: [5, 10, 20, 50],//分頁步進值
            sidePagination: "server",//服務端分頁
            contentType: "application/x-www-form-urlencoded",//請求數(shù)據(jù)內(nèi)容格式 默認是 application/json 自己根據(jù)格式自行服務端處理
            dataType: "json",//期待返回數(shù)據(jù)類型
            method: "post",//請求方式
            searchAlign: "left",//查詢框對齊方式
            queryParamsType: "limit",//查詢參數(shù)組織方式
            queryParams: function getParams(params) {
                //params obj
                params.other = "otherInfo";
                return params;
            },
            searchOnEnterKey: false,//回車搜索
            showRefresh: true,//刷新按鈕
            showColumns: true,//列選擇按鈕
            buttonsAlign: "left",//按鈕對齊方式
            toolbar: "#toolbar",//指定工具欄
            toolbarAlign: "right",//工具欄對齊方式
            columns: [
                {
                    title: "全選",
                    field: "select",
                    checkbox: true,
                    width: 20,//寬度
                    align: "center",//水平
                    valign: "middle"//垂直
                },
                {
                    title: "ID",//標題
                    field: "id",//鍵名
                    sortable: true,//是否可排序
                    order: "desc"//默認排序方式
                },
                {
                    field: "name",
                    title: "NAME",
                    sortable: true,
                    titleTooltip: "this is name"
                },
                {
                    field: "age",
                    title: "AGE",
                    sortable: true,
                },
                {
                    field: "info",
                    title: "INFO[using-formatter]",
                    formatter: 'infoFormatter',//對本列數(shù)據(jù)做格式化
                }
            ],
            onClickRow: function(row, $element) {
                //$element是當前tr的jquery對象
                $element.css("background-color", "green");
            },//單擊row事件
            locale: "zh-CN", //中文支持
            detailView: false, //是否顯示詳情折疊
            detailFormatter: function(index, row, element) {
                var html = '';
                $.each(row, function(key, val){
                    html += "<p>" + key + ":" + val +  "</p>"
                });
                return html;
            }
        });

        $("#addRecord").click(function(){
            alert("name:" + $("#name").val() + " age:" +$("#age").val());
        });
    })

    function tableHeight() {
        return $(window).height() - 50;
    }
    /**
     * 列的格式化函數(shù) 在數(shù)據(jù)從服務端返回裝載前進行處理
     * @param  {[type]} value [description]
     * @param  {[type]} row   [description]
     * @param  {[type]} index [description]
     * @return {[type]}       [description]
     */
    function infoFormatter(value, row, index)
    {
        return "id:" + row.id + " name:" + row.name + " age:" + row.age;
    }
</script>
</body>
</html>

服務端:只需在接到請求時返回json數(shù)組就行了,是json數(shù)組哦,不是單個對象,不然就數(shù)據(jù)展示不出來。

注意bootstrap table 可以前端分頁也可以后端分頁,這里我們使用的是后端分頁,后端分頁時需返回含有

total:總記錄數(shù) 這個鍵值好像是固定的,我看文檔沒找到可以修改成別的

rows: 記錄集合 鍵值可以修改  dataField 自己定義成自己想要的就好

{
"total":200,
"rows":[
{"id":1, "name":"sallency", "age": 26},
{"id":1, "name":"sallency", "age": 26},
{"id":1, "name":"sallency", "age": 26},
{"id":1, "name":"sallency", "age": 26},
{"id":1, "name":"sallency", "age": 26}]
}

但是這可能會有請求時數(shù)據(jù)賦值不了的情況,那時你就會干著急了,下面還可以使用如下方式進行數(shù)據(jù)渲染。這個效果和上面一個不一樣,這里就不上圖了。同樣第一步要引入官網(wǎng)所要求的的css/js等文件。

var $table = $("#product");
    $table.bootstrapTable({
        url: "http://192.168.6.240:8080/form", 
        dataType: "json",
        contentType: "application/x-www-form-urlencoded",

        // toolbar: '#toolbar',                //工具按鈕用哪個容器
         striped: true,                      //是否顯示行間隔色
         cache: false,                       //是否使用緩存,默認為true,所以一般情況下需要設置一下這個屬性(*)
         pagination: true,                   //是否顯示分頁(*)
         sortable: false,                     //是否啟用排序
         sortOrder: "desc",                   //排序方式
      
         sidePagination: "client",           //分頁方式:client客戶端分頁,server服務端分頁(*)
         pageNumber:1,                       //初始化加載第一頁,默認第一頁
         pageSize: 10,                       //每頁的記錄行數(shù)(*)
         pageList:[5,10,20,30],//分頁步進值       //可供選擇的每頁的行數(shù)(*)
        // search:true,               //是否顯示表格搜索,此搜索是客戶端搜索,不會進服務端,所以,個人感覺意義不大
        // strictSearch: true,
         oolbarAlign:'right',//工具欄對齊方式
         buttonsAlign:'right',//按鈕對齊方式
        // showColumns: true,                  //是否顯示所有的列
        // showRefresh: true,                  //是否顯示刷新按鈕
         minimumCountColumns: 2,             //最少允許的列數(shù)
         clickToSelect: true,                //是否啟用點擊選中行
         //height: 500,                        //行高,如果沒有設置height屬性,表格自動根據(jù)記錄條數(shù)覺得表格高度
         uniqueId: "id",                     //每一行的唯一標識,一般為主鍵列
        // showToggle:true,                    //是否顯示詳細視圖和列表視圖的切換按鈕
         cardView: false,                    //是否顯示詳細視圖
        // detailView: false,                   //是否顯示父子表onEditableSave
        // singleSelect: false,
        // striped: true, //是否顯示行間隔色
        // cache: false, //是否使用緩存,默認為true,所以一般情況下需要設置一下這個屬性(*)
        // sortable: true, //是否啟用排序 
        // pagination: true,   //顯示分頁按鈕
        // sortName:"starttime",
        // sortOrder:"desc", //默認排序
        // pageNumber: 1, //初始化加載第一頁,默認第一頁
        // pageSize: 10,   //默認顯示的每頁個數(shù)
        // showRefresh: true,                  //是否顯示刷新按鈕
        // showPaginationSwitch: true,       //是否顯示選擇分頁數(shù)按鈕
        // queryParamsType: '', //默認值為 'limit' ,在默認情況下 傳給服務端的參數(shù)為:offset,limit,sort // 設置為 '' 在這種情況下傳給服務器的參數(shù)為:pageSize,pageNumber
         queryParams:function(params){
             var temp = {     
                pageSize: params.pageSize,   //頁面大小
                pageNumber: params.pageNumber,  //頁碼
                 table_data:tempdata,
               
            }
            return temp;
        },
        responseHandler:function(res){
            //動態(tài)渲染表格之前獲取有后臺傳遞的數(shù)據(jù)時,用于獲取出除去本身渲染所需的數(shù)據(jù)的額外參數(shù)
            //詳見此函數(shù)參數(shù)的api
            return res;
        },
       // search: true, //顯示搜索框(客戶端搜索)
       //sidePagination: "server", //服務端處理分頁
       // showToggle:true,                    //是否顯示詳細視圖和列表視圖的切換按鈕
        cardView: false,                    //是否顯示詳細視圖
       // detailView: false,                   //是否顯示父子表
        columns: [{
            title : '備注',
            field : 'code',
            align : 'center',
            width :  100,
            valign : 'middle',
           
        },{
            title : '操作',
            field : 'name',
            align : 'center',
            width :  120 ,
            valign : 'middle',
           
        },
        {
            title : '編碼',
            field : 'calcMode',
            align : 'center',
            width :  120 ,
            valign : 'middle',
           
        }],
      
        onLoadSuccess: function(){  //加載成功時執(zhí)行  
            alert("加載數(shù)據(jù)成功");  
        },  
        onLoadError: function(){  //加載失敗時執(zhí)行  
            alert("加載數(shù)據(jù)失敗");  
        }        
    });

};

會使用之后是不是覺得比自己寫的table更好用多了,還不用寫一大堆js和div等,還有更多功能可以去官網(wǎng)了解怎么使用。

看完上述內(nèi)容,你們掌握如何用bootstrap table實現(xiàn)數(shù)據(jù)表格的方法了嗎?如果還想學到更多技能或想了解更多相關內(nèi)容,歡迎關注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI