"""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">|<</button>
<button type="button" id="btn-prev"><</button>
<span id="pg-num">Page 1 of 1</span>
<button type="button" id="btn-next">></button>
<button type="button" id="btn-last">>|</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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/jeasyui-datagrid-datagrid2-lab/explore-datagrid-datagrid2.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-datagrid-datagrid2.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a976.zip
课程关联工程包(登记关联68章) · 含当前章节或实例 · mbskycom202612a964.zip