jQuery EasyUI 樹形菜單 - 樹形網格添加分頁
本教程展示如何向帶有動態加載特性的樹形網格(TreeGrid)添加分頁。
創建樹形網格(TreeGrid)
啟用樹形網格(TreeGrid)的分頁特性,必須添加 'pagination:true' 屬性,這樣頁面加載時就會向伺服器發送 'page' 和 'rows' 參數。
<table title="Products" class="easyui-treegrid" style="width:700px;height:300px"
data-options="
url: 'treegrid4_getdata.php',
rownumbers: true,
pagination: true,
pageSize: 2,
pageList: [2,10,20],
idField: 'id',
treeField: 'name',
onBeforeLoad: function(row,param){
if (!row) { // load top level rows
param.id = 0; // set id=0, indicate to load new page rows
}
}
">
<thead>
<tr>
<th field="name" width="250">Name</th>
<th field="quantity" width="100" align="right">Quantity</th>
<th field="price" width="150" align="right" formatter="formatDollar">Price</th>
<th field="total" width="150" align="right" formatter="formatDollar">Total</th>
</tr>
</thead>
</table>
伺服器端代碼
treegrid4_getdata.php
$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
$offset = ($page-1)*$rows;
$id = isset($_POST['id']) ? intval($_POST['id']) : 0;
include 'conn.php';
$result = array();
if ($id == 0){
$rs = mysql_query("select count(*) from products where parentId=0");
$row = mysql_fetch_row($rs);
$result["total"] = $row[0];
$rs = mysql_query("select * from products where parentId=0 limit $offset,$rows");
$items = array();
while($row = mysql_fetch_array($rs)){
$row['state'] = has_child($row['id']) ? 'closed' : 'open';
array_push($items, $row);
}
$result["rows"] = $items;
} else {
$rs = mysql_query("select * from products where parentId=$id");
while($row = mysql_fetch_array($rs)){
$row['state'] = has_child($row['id']) ? 'closed' : 'open';
$row['total'] = $row['price']*$row['quantity'];
array_push($result, $row);
}
}
echo json_encode($result);
function has_child($id){
$rs = mysql_query("select count(*) from products where parentId=$id");
$row = mysql_fetch_array($rs);
return $row[0] > 0 ? true : false;
}
發送到伺服器的參數包括:
- page:要加載的當前頁面。
- rows:頁面尺寸大小。
- id:父行的 id 值,從伺服器返回的行將被添加。
當展開一個行節點時,'id' 值是大於 0 的。 當改變頁碼時,'id' 值應該被設置為 0 來放置加載子行。
