1. 程式人生 > >Bootstrap Table 後端分頁

Bootstrap Table 後端分頁

之前一直用的前端分頁,在資料不是太多的情況下,前端分頁還是很方便的,也可以使用自帶的搜尋等功能,如果資料量比較多的情況就要使用後端分頁。

實現的原理:前端把offset和limit(每一頁顯示的數量)傳送給後端,後端查詢資料庫 返回JSON,前端根據後端返回的total展示出pagination。

返回的JSON格式

{
    "total": 25,
    "rows": [
    {},
    {},
    ...
    ]
}

前端主要設定

sidePagination: "server",
pageNumber: 1,
queryParams:queryParams,

queryParams是一個函式,

	function queryParams(params) {
	  console.log(JSON.stringify(params)) // {"order":"asc","offset":0,"limit":10}
		return {
			offset:params.offset,
			limit:params.limit
		}
	}

完整的程式碼

<table class="table-striped table-hasthead" id="tableTest1">
    <thead>
        <tr>
            <th data-sortable="true" data-field="id">Id</th>
            <th data-field="name">Name</th>
            <th data-sortable="true" data-field="url">Website</th>
            <th data-field="alex">Texa</th>
            <th data-field="country">Country</th>
        </tr>
    </thead>
</table>
    $(function() {
        var url = "selectBtTable.php?action=init_data_list";
        $('#tableTest1').bootstrapTable({
            height: $(window).height() - 460,
            url: url,
            method: 'POST', //預設是GET方式請求
            contentType: "application/x-www-form-urlencoded",
            search: true,
            pagination: true,
            sidePagination: "server",
            pageNumber: 1,
            queryParams: queryParams,
        });
    });

    使用GET請求會把引數放在URL中傳送給後端
    selectBtTable.php?action=init_data_list&offset=0&limit=10

   如果是POST請求 一定要加上contentType: "application/x-www-form-urlencoded"

後端PHP 簡單程式碼

<?php
$action = $_GET['action'];
//var_dump($action);
switch ($action) {
    case 'init_data_list':
        init_data_list();
        break;

    case 'data_list':
        data_list();
        break;

    case 'del_row':
        del_row();
        break;

    case 'edit_row':
        edit_row();
        break;
}

function init_data_list()
{
	$offset = $_POST['offset'];
	//$offset = intval($offset); 可以不用轉換
	$limit = $_POST['limit'];
	//var_dump($offset);
    //$sql = "SELECT * FROM website"; select * from clerk limit {$sql},{$pagesize}
	$sql = "SELECT * FROM website limit {$offset},{$limit}";
	// SELECT * FROM products LIMIT 0,8; 
    // SELECT * FROM products LIMIT 8 OFFSET 0; (在mysql 5以後支援這種寫法)
    $query = query_sql($sql);
    while ($row = $query->fetch_assoc()) {
        $data[] = $row;
    }

	$sql = "SELECT * FROM website";
	$query=query_sql($sql);
	$total=mysqli_num_rows($query);
	$result["total"] = $total; // count($data);
	$result["rows"] = $data;
	//$result["rows"] = array_slice($data, $offset, $limit);
    echo json_encode($result);
}

function query_sql()
{
    $mysqli = new mysqli("127.0.0.1", "root", "123", "demodb");
    $sqls = func_get_args();
    foreach ($sqls as $s) {
        $query = $mysqli->query($s);
    }
    $mysqli->close();
    return $query;
}
?>