树形网格添加分页


本教程展示如何向带有动态加载特性的树形网格(TreeGrid)添加分页。

创建树形网格(TreeGrid)

启用树形网格(TreeGrid)的分页特性,必须添加 'pagination:true' 属性,这样页面加载时就会向服务器发送 'page' 和 'rows' 参数。

  1. <table title="Products" class="easyui-treegrid" style="width:700px;height:300px"
  2. data-options="
  3. url: 'treegrid4_getdata.php',
  4. rownumbers: true,
  5. pagination: true,
  6. pageSize: 2,
  7. pageList: [2,10,20],
  8. idField: 'id',
  9. treeField: 'name',
  10. onBeforeLoad: function(row,param){
  11. if (!row) { // load top level rows
  12. param.id = 0; // set id=0, indicate to load new page rows
  13. }
  14. }
  15. ">
  16. <thead>
  17. <tr>
  18. <th field="name" width="250">Name</th>
  19. <th field="quantity" width="100" align="right">Quantity</th>
  20. <th field="price" width="150" align="right" formatter="formatDollar">Price</th>
  21. <th field="total" width="150" align="right" formatter="formatDollar">Total</th>
  22. </tr>
  23. </thead>
  24. </table>

服务器端代码

treegrid4_getdata.php

  1. $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
  2. $rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
  3. $offset = ($page-1)*$rows;
  4.  
  5. $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
  6.  
  7. include 'conn.php';
  8.  
  9. $result = array();
  10. if ($id == 0){
  11. $rs = mysql_query("select count(*) from products where parentId=0");
  12. $row = mysql_fetch_row($rs);
  13. $result["total"] = $row[0];
  14. $rs = mysql_query("select * from products where parentId=0 limit $offset,$rows");
  15. $items = array();
  16. while($row = mysql_fetch_array($rs)){
  17. $row['state'] = has_child($row['id']) ? 'closed' : 'open';
  18. array_push($items, $row);
  19. }
  20. $result["rows"] = $items;
  21. } else {
  22. $rs = mysql_query("select * from products where parentId=$id");
  23. while($row = mysql_fetch_array($rs)){
  24. $row['state'] = has_child($row['id']) ? 'closed' : 'open';
  25. $row['total'] = $row['price']*$row['quantity'];
  26. array_push($result, $row);
  27. }
  28. }
  29.  
  30. echo json_encode($result);
  31.  
  32. function has_child($id){
  33. $rs = mysql_query("select count(*) from products where parentId=$id");
  34. $row = mysql_fetch_array($rs);
  35. return $row[0] > 0 ? true : false;
  36. }

发送到服务器的参数包括:

  • page:要加载的当前页面。
  • rows:页面尺寸大小。
  • id:父行的 id 值,从服务器返回的行将被添加。

当展开一个行节点时,'id' 值是大于 0 的。 当改变页码时,'id' 值应该被设置为 0 来放置加载子行。

下载 jQuery EasyUI 实例

下载地址