以前一直用的前端分頁,在數據不是太多的狀況下,前端分頁仍是很方便的,也能夠使用自帶的搜索等功能,若是數據量比較多的狀況就要使用後端分頁。javascript
實現的原理:前端把offset和limit(每一頁顯示的數量)發送給後端,後端查詢數據庫 返回JSON,前端根據後端返回的total展現出pagination。php
返回的JSON格式html
{ "total": 25, "rows": [ {}, {}, ... ] }
前端主要設置前端
sidePagination: "server", pageNumber: 1, queryParams:queryParams,
queryParams是一個函數,java
function queryParams(params) { console.log(JSON.stringify(params)) // {"order":"asc","offset":0,"limit":10} return { offset:params.offset, limit:params.limit } }
完整的代碼mysql
<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=10web
若是是POST請求 必定要加上contentType: "application/x-www-form-urlencoded"sql
後端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; } ?>