蓝色天空.知识 · 实践 · 创造
我的收藏
jQuery EasyUI 教程目录 68章
课程介绍
jQuery EasyUI / LEARN BY DOING

jEasyUI 添加分页组件

核对 DataGrid 开启 pagination="true" 后的远程加载协议(POST page 与 rows)、服务端 total/rows JSON 格式及翻页与切换每页条数实测。

学完这一章,你能够

  • 核对 DataGrid 开启 pagination="true" 后的远程加载协议(POST page 与 rows)、服务端 total/rows JSON 格式及翻页与切换每页条数实测。

启用 DataGrid 远程分页工具栏与请求参数

为了从服务端按页拉取大数据集并减少单次传输量,可在 `<table class="easyui-datagrid">` 上指定远程接口 `url` 并设置 `pagination="true"`(常搭配 `rownumbers="true"` 显示行号)。

启用分页后,组件会在表格底部自动生成包含页码切换、页大小下拉框与范围统计的分页工具栏,并在每次加载或翻页时向服务端发送两项核心参数:`page`(当前页码,从 `1` 开始计数)与 `rows`(每页期望返回的记录数)。

服务端分页查询协议与离线回环实测

服务端接收到 `page` 与 `rows` 后计算起始偏移量 `offset = (page - 1) * rows`,先统计总记录数填入 `total`,再按 `LIMIT offset, rows` 查询当前页数据填入 `rows` 数组并输出 JSON(原示例中的旧版 PHP `mysql_query` 已废弃,生产环境应改用 PDO 预处理整型绑定)。本站构建 25 条确定性商品数据的本地 `127.0.0.1` 回环服务并在无头 Chromium 中实测:首次加载自动 POST `{page: 1, rows: 10, offset: 0}`,表格渲染 `EST-01`–`EST-10` 共 10 行,底栏显示 `Page 1 of 3` 与 `Displaying 1 to 10 of 25 items`;点击下一页拉取 `EST-11` 起的数据,点击末页发送 `{page: 3, rows: 10, offset: 20}` 渲染最后 `5` 行(`EST-21`–`EST-25`)并显示 `Displaying 21 to 25 of 25 items`;将每页条数由 `10` 切换为 `20` 时自动重置回第 `1` 页(POST `{page: 1, rows: 20, offset: 0}`),总页数变为 `2` 页并显示 `Displaying 1 to 20 of 25 items`。

来源示例压缩包 `jeasyui-datagrid-datagrid2.zip` 未联网下载,上述回环实验已完整核验分页参数、偏移切片与页大小重置逻辑。

运行 DataGrid 远程分页参数(page/rows)与翻页切片离线回环实验

含完整源码 · 238 行
展开查看收起
python
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 45: DataGrid Pagination Component."""
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import threading
from urllib.parse import parse_qs
from playwright.sync_api import sync_playwright

DATASET = [
    {
        "itemid": f"EST-{i:02d}",
        "productid": f"PR-{(i - 1) // 5 + 1:02d}",
        "listprice": f"{10 + i * 1.5:.2f}",
        "unitcost": f"{6 + i * 0.8:.2f}",
        "attr1": f"Attribute {i}",
        "status": "P",
    }
    for i in range(1, 26)
]

HTML_PAGE = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>EasyUI DataGrid Pagination Offline Lab</title>
<style>
  body { font-family: sans-serif; margin: 16px; font-size: 13px; }
  .dg-wrap { width: 600px; border: 1px solid #95b8e7; }
  .dg-title { background: #e0ecff; padding: 6px 8px; font-weight: bold; }
  table#tt { width: 100%; border-collapse: collapse; }
  table#tt th, table#tt td { border: 1px solid #ccc; padding: 4px 6px; }
  table#tt th { background: #f4f4f4; }
  .datagrid-pager { display: flex; align-items: center; gap: 6px; padding: 5px 8px; background: #f4f4f4; border-top: 1px solid #ccc; font-size: 12px; }
  .pager-info { margin-left: auto; }
</style>
</head>
<body>
<div class="dg-wrap">
  <div class="dg-title">Load Data</div>
  <table id="tt">
    <thead><tr>
      <th style="width:28px">#</th>
      <th>Item ID</th><th>Product ID</th><th>List Price</th><th>Unit Cost</th><th>Attribute</th><th>Status</th>
    </tr></thead>
    <tbody></tbody>
  </table>
  <div class="datagrid-pager">
    <select id="pg-size"><option value="10" selected>10</option><option value="20">20</option></select>
    <button type="button" id="btn-first">|&lt;</button>
    <button type="button" id="btn-prev">&lt;</button>
    <span id="pg-num">Page 1 of 1</span>
    <button type="button" id="btn-next">&gt;</button>
    <button type="button" id="btn-last">&gt;|</button>
    <span id="pg-info" class="pager-info"></span>
  </div>
</div>

<script>
const state = { page: 1, rows: 10, total: 0, loadCount: 0 };

async function loadPage(page, rows) {
  state.page = page;
  state.rows = rows;
  const resp = await fetch("/datagrid2_getdata", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: `page=${page}&rows=${rows}`
  });
  const data = await resp.json();
  state.total = data.total;
  const totalPages = Math.max(1, Math.ceil(data.total / rows));
  const offset = (page - 1) * rows;
  const tbody = document.querySelector("#tt tbody");
  tbody.innerHTML = data.rows.map((r, i) => `
    <tr data-itemid="${r.itemid}">
      <td>${offset + i + 1}</td><td>${r.itemid}</td><td>${r.productid}</td>
      <td style="text-align:right">${r.listprice}</td><td style="text-align:right">${r.unitcost}</td>
      <td>${r.attr1}</td><td style="text-align:center">${r.status}</td>
    </tr>`).join("");
  const start = data.rows.length ? offset + 1 : 0;
  const end = offset + data.rows.length;
  document.getElementById("pg-num").textContent = `Page ${page} of ${totalPages}`;
  document.getElementById("pg-info").textContent = `Displaying ${start} to ${end} of ${data.total} items`;
  state.loadCount += 1;
}

document.getElementById("btn-first").addEventListener("click", () => loadPage(1, state.rows));
document.getElementById("btn-prev").addEventListener("click", () => loadPage(Math.max(1, state.page - 1), state.rows));
document.getElementById("btn-next").addEventListener("click", () => {
  const maxP = Math.max(1, Math.ceil(state.total / state.rows));
  loadPage(Math.min(maxP, state.page + 1), state.rows);
});
document.getElementById("btn-last").addEventListener("click", () => {
  const maxP = Math.max(1, Math.ceil(state.total / state.rows));
  loadPage(maxP, state.rows);
});
document.getElementById("pg-size").addEventListener("change", (ev) => {
  loadPage(1, parseInt(ev.target.value, 10));
});

window.lab = { state };
loadPage(1, 10);
</script>
</body>
</html>
"""


def make_handler(post_log):
    class Handler(BaseHTTPRequestHandler):
        def log_message(self, fmt, *args):
            pass

        def do_GET(self):
            if self.path == "/":
                self.send_response(200)
                self.send_header("Content-Type", "text/html; charset=utf-8")
                self.end_headers()
                self.wfile.write(HTML_PAGE.encode("utf-8"))
            else:
                self.send_response(404)
                self.end_headers()

        def do_POST(self):
            if self.path == "/datagrid2_getdata":
                length = int(self.headers.get("Content-Length", "0"))
                qs = parse_qs(self.rfile.read(length).decode("utf-8"))
                page = int(qs.get("page", ["1"])[0])
                rows = int(qs.get("rows", ["10"])[0])
                offset = (page - 1) * rows
                post_log.append({"page": page, "rows": rows, "offset": offset})
                payload = {"total": len(DATASET), "rows": DATASET[offset:offset + rows]}
                self.send_response(200)
                self.send_header("Content-Type", "application/json")
                self.end_headers()
                self.wfile.write(json.dumps(payload).encode("utf-8"))
            else:
                self.send_response(404)
                self.end_headers()
    return Handler


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


def main():
    post_log = []
    server = HTTPServer(("127.0.0.1", 0), make_handler(post_log))
    port = server.server_address[1]
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()
    cases = []
    try:
        with sync_playwright() as p:
            browser = launch_browser(p)
            page = browser.new_page()
            page.goto(f"http://127.0.0.1:{port}/")
            page.wait_for_function("() => window.lab.state.loadCount === 1")

            # Case 1: Initial page 1 POST params (page=1, rows=10) & pager text
            res1 = page.evaluate("""() => {
                const trs = Array.from(document.querySelectorAll("#tt tbody tr"));
                return {
                    rowCount: trs.length,
                    firstId: trs[0].dataset.itemid,
                    lastId: trs[trs.length - 1].dataset.itemid,
                    pgNum: document.getElementById("pg-num").textContent,
                    pgInfo: document.getElementById("pg-info").textContent
                };
            }""")
            res1["serverPost"] = post_log[0]
            exp1 = {
                "rowCount": 10,
                "firstId": "EST-01",
                "lastId": "EST-10",
                "pgNum": "Page 1 of 3",
                "pgInfo": "Displaying 1 to 10 of 25 items",
                "serverPost": {"page": 1, "rows": 10, "offset": 0},
            }
            cases.append(dict(name="pagination_initial_page1_post_params", expected=exp1, actual=res1, passed=(res1 == exp1)))

            # Case 2: Next page (page=2) and Last page (page=3, 5 remaining rows)
            page.click("#btn-next")
            page.wait_for_function("() => window.lab.state.loadCount === 2")
            p2_first = page.evaluate("() => document.querySelector('#tt tbody tr:first-child').dataset.itemid")
            page.click("#btn-last")
            page.wait_for_function("() => window.lab.state.loadCount === 3")
            res2 = page.evaluate("""(p2First) => {
                const trs = Array.from(document.querySelectorAll("#tt tbody tr"));
                return {
                    page2FirstId: p2First,
                    lastPageRowCount: trs.length,
                    lastPageFirstId: trs[0].dataset.itemid,
                    lastPageLastId: trs[trs.length - 1].dataset.itemid,
                    pgInfo: document.getElementById("pg-info").textContent
                };
            }""", p2_first)
            res2["lastPost"] = post_log[-1]
            exp2 = {
                "page2FirstId": "EST-11",
                "lastPageRowCount": 5,
                "lastPageFirstId": "EST-21",
                "lastPageLastId": "EST-25",
                "pgInfo": "Displaying 21 to 25 of 25 items",
                "lastPost": {"page": 3, "rows": 10, "offset": 20},
            }
            cases.append(dict(name="pagination_next_and_last_page_offset", expected=exp2, actual=res2, passed=(res2 == exp2)))

            # Case 3: Changing pageSize from 10 to 20 resets page to 1
            page.select_option("#pg-size", "20")
            page.wait_for_function("() => window.lab.state.loadCount === 4")
            res3 = page.evaluate("""() => ({
                rowCount: document.querySelectorAll("#tt tbody tr").length,
                pgNum: document.getElementById("pg-num").textContent,
                pgInfo: document.getElementById("pg-info").textContent
            })""")
            res3["serverPost"] = post_log[-1]
            exp3 = {
                "rowCount": 20,
                "pgNum": "Page 1 of 2",
                "pgInfo": "Displaying 1 to 20 of 25 items",
                "serverPost": {"page": 1, "rows": 20, "offset": 0},
            }
            cases.append(dict(name="pagination_change_page_size_resets_page", expected=exp3, actual=res3, passed=(res3 == exp3)))

            browser.close()
    finally:
        server.shutdown()
        server.server_close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
核对 25 条数据下首页 page=1/rows=10、末页 page=3/offset=20 渲染 5 行,以及切换 pageSize=20 自动重置回第 1 页(共 2 页)。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a976.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:jQuery EasyUI

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a976.zip

下载课程关联工程包:jQuery EasyUI

课程关联工程包(登记关联68章) · 含当前章节或实例 · mbskycom202612a964.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

必须包含 total(总记录条数,用于计算总页数)与 rows(当前页记录数组);偏移量计算公式为 offset = (page - 1) * rows,其中 page 起始值为 1。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习