bootstrap table 實例

bootstrap table 封裝了一套完善的數據表格組件,把下面的代碼複製一下估計你須要的基本功能都有了,沒有的再看看手冊對比着我給的實例也能很快的熟悉了javascript

客戶端php

<!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>
                                <h4 class="modal-title" id="myModalLabel">添加記錄</h4>
                            </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() {
            //根據窗口調整表格高度
            $(window).resize(function() {
                $('#mytab').bootstrapTable('resetView', {
                    height: tableHeight()
                })
            })

            $('#mytab').bootstrapTable({
                url: "index.php",//數據源
                dataField: "rows",//服務端返回數據鍵值 就是說記錄放的鍵值是rows,分頁時使用總記錄數的鍵值爲total
                height: tableHeight(),//高度調整
                search: true,//是否搜索
                pagination: true,//是否分頁
                pageSize: 20,//單頁記錄數
                pageList: [5, 10, 20, 50],//分頁步進值
                sidePagination: "server",//服務端分頁
                contentType: "application/x-www-form-urlencoded",//請求數據內容格式 默認是 application/json 本身根據格式自行服務端處理
                dataType: "json",//期待返回數據類型
                method: "post",//請求方式
                searchAlign: "left",//查詢框對齊方式
                queryParamsType: "limit",//查詢參數組織方式
                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',//對本列數據作格式化
                    }
                ],
                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;
        }
        /**
         * 列的格式化函數 在數據從服務端返回裝載前進行處理
         * @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>

服務端:css

<?php
/**
 * 服務端模擬數據
 */

//前端指望數據爲json
header("Content-Type:application/json;charset=utf-8");
//post 請求 請求內容類型爲 application/x-www-form-urlencoded 若是是 application/json 則須要另行處理 $_POST 數組不會被填充

//爲了保持模擬的數據
session_start();

if ($_SESSION['emulate_data']) {
    //已生成
} else {
    $list = [];
    //第一次會模擬個數據
    for($i = 1; $i < 50; $i ++) {
        $list[] = [
                "id" => $i,
                "name" => substr(str_shuffle(implode('', range('a', 'z'))), 0, 5),
                "age" => mt_rand(10, 30)
            ];
    }
    $_SESSION['emulate_data'] = $list;
}

$list_temp = [];
//檢索
if (isset($_POST['search']) && !empty($_POST['search'])) {
    foreach ($_SESSION['emulate_data'] as $key => $row) {
        if (strpos($row['name'], $_POST['search']) !== false 
        || strpos($row['age'], $_POST['search']) !== false) {
            $list_temp[] = $_SESSION['emulate_data'][$key];
        }
    }
} else {
    $list_temp = $_SESSION['emulate_data'];
}
//排序
if (isset($_POST['sort'])) {
    $temp = [];
    foreach ($list_temp as $row) {
        $temp[] = $row[$_POST['sort']];
    }
    //php的多維排序
    array_multisort($temp,
        $_POST['sort'] == 'name' ? SORT_STRING : SORT_NUMERIC,
        $_POST['order'] == 'asc' ? SORT_ASC : SORT_DESC,
        $list_temp
    );
}

//分頁時須要獲取記錄總數,鍵值爲 total
$result["total"] = count($list_temp);
//根據傳遞過來的分頁偏移量和分頁量截取模擬分頁 rows 能夠根據前端的 dataField 來設置
$result["rows"] = array_slice($list_temp, $_POST['offset'], $_POST['limit']);

echo json_encode($result);

須要注意的是html

一、bootstrap table 能夠前端分頁也能夠後端分頁,這裏咱們使用的是後端分頁,後端分頁時需返回含有前端

total:總記錄數 這個鍵值好像是固定的,我看文檔沒找到能夠修改爲別的java

rows: 記錄集合 鍵值能夠修改  dataField 本身定義成本身想要的就好jquery

{
    "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}]
}

如上的json數據(固然我前臺設置的指望數據類型是json,php 直接encode一個 ["total"=>200, "rows"=>[[],[],][,][,]]的數組就完事了,方便)json

二、且其請求後端是傳遞的內容格式默認爲 application/json 我本身習慣用方便的 x-www-form-urlencodedbootstrap

相關文章
相關標籤/搜索