jEasyUI 添加查询功能
核对 DataGrid 配合分页工具栏、doSearch 调用 load 传递过滤参数,以及服务端按前缀条件过滤并返回 {total, rows} JSON 的前后端回环实测。
学完这一章,你能够
- 核对 DataGrid 配合分页工具栏、doSearch 调用 load 传递过滤参数,以及服务端按前缀条件过滤并返回 {total, rows} JSON 的前后端回环实测。
为分页数据网格集成查询工具栏
在数据库驱动的后台列表中,常见需求是将服务端分页数据加载到 DataGrid,并依据用户在工具栏输入的关键词实时过滤展示结果。
前端先声明开启行号与分页的 DataGrid(`rownumbers="true"`、`pagination="true"`、`toolbar="#tb"`、`url="datagrid24_getdata.php"`),再在 `<div id="tb">` 中放置 `Item ID` 输入框(`#itemid`)、`Product ID` 输入框(`#productid`)与触发 `doSearch()` 的 `Search` 按钮。
点击查询按钮后,`doSearch()` 调用 `$('#tt').datagrid('load', { itemid, productid })`,将两个筛选字段连同分页参数 POST 至服务端,并自动重置回第 1 页重新渲染结果。
服务端分页查询协议与本地回环实测
服务端接收 `page`、`rows`、`itemid`、`productid` 四个表单参数,按 `offset = (page - 1) * rows` 计算分页偏移,使用前缀匹配条件分别统计总记录数 `total` 与查询当前页记录数组 `rows`,最终输出 `{"total": ..., "rows": [...]}` JSON。注意早期示例中的 PHP `mysql_query` 与 `mysql_real_escape_string` 已在 PHP 7 中移除,工程实践必须改用 PDO/SQLite 参数化预处理语句防注入。本站搭建 `127.0.0.1` 本地回环 HTTP + SQLite 服务驱动 Chromium 实测:初始第 1 页返回 `total=12`、行号 `1..5`;输入 `itemid="EST-1"` 与 `productid="RP-SN"` 后 POST 携带精确过滤参数并返回 2 条匹配记录(`['EST-11', 'EST-12']`);位于第 2 页时查询不存在词 `"NOPE"`,自动复位至第 1 页并渲染 `total=0` 空结果。
原始示例压缩包 `jeasyui-datagrid-datagrid24.zip` 未发起网络下载并已登记于附件清单;运行本地回环实验脚本即可离线体验完整的分页与组合查询联调。
运行 DataGrid 工具栏分页查询与本地 HTTP/SQLite 回环服务实验
"""Offline Playwright Chromium + loopback HTTP/SQLite lab for jQuery EasyUI Ch 23: DataGrid Search."""
import json
import sqlite3
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs
from playwright.sync_api import sync_playwright
SEED_ITEMS = [
("EST-1", "FI-SW-01", 16.5, 10.0, "Large", "P"),
("EST-10", "K9-DL-01", 18.5, 12.0, "Spotted Adult Female", "P"),
("EST-11", "RP-SN-01", 28.5, 12.0, "Venomless", "P"),
("EST-12", "RP-SN-01", 26.5, 12.0, "Rattleless", "P"),
("EST-13", "RP-LI-02", 18.5, 12.0, "Green Adult", "P"),
("EST-14", "FL-DSH-01", 58.5, 12.0, "Tailless", "P"),
("EST-15", "FL-DSH-01", 23.5, 12.0, "With tail", "P"),
("EST-16", "FL-DLH-02", 93.5, 12.0, "Adult Female", "P"),
("EST-17", "FL-DLH-02", 93.5, 12.0, "Adult Male", "P"),
("EST-18", "AV-CB-01", 193.5, 92.0, "Adult Male", "P"),
("EST-20", "FI-SW-02", 15.5, 9.0, "Small", "P"),
("EST-21", "K9-PO-02", 22.0, 14.0, "Male Puppy", "P"),
]
HTML_DOC = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>EasyUI DataGrid Search Offline Lab</title>
<style>
body { font-family: sans-serif; margin: 12px; }
.dg-panel { width: 640px; border: 1px solid #95b8e7; }
.dg-title { background: #e0ecff; padding: 6px 8px; font-weight: 600; font-size: 13px; border-bottom: 1px solid #95b8e7; }
#tb { padding: 5px; background: #f4f4f4; border-bottom: 1px solid #ddd; font-size: 12px; }
#tb input { line-height: 22px; border: 1px solid #ccc; width: 100px; margin-right: 8px; }
table { width: 100%; border-collapse: collapse; font-size: 12px; }
th, td { border: 1px solid #ddd; padding: 4px 6px; }
th { background: #efefef; }
.dg-pager { padding: 5px 8px; background: #f4f4f4; border-top: 1px solid #ddd; font-size: 12px; display: flex; gap: 8px; align-items: center; }
</style>
</head>
<body>
<div class="dg-panel">
<div class="dg-title">Load Data</div>
<div id="tb">
<span>Item ID:</span><input id="itemid">
<span>Product ID:</span><input id="productid">
<a href="#" id="btn-search" class="easyui-linkbutton" onclick="doSearch();return false;">Search</a>
</div>
<table id="tt">
<thead>
<tr>
<th width="30">#</th>
<th width="80">Item ID</th>
<th width="80">Product ID</th>
<th width="80" style="text-align:right">List Price</th>
<th width="80" style="text-align:right">Unit Cost</th>
<th width="150">Attribute</th>
<th width="60" style="text-align:center">Status</th>
</tr>
</thead>
<tbody></tbody>
</table>
<div class="dg-pager">
<button id="btn-prev" type="button">Prev</button>
<button id="btn-next" type="button">Next</button>
<span id="pager-info"></span>
</div>
</div>
<script>
const state = { page: 1, rows: 5, queryParams: { itemid: '', productid: '' }, total: 0, data: [], lastPayload: null };
async function loadPage(pageNum, extraParams) {
if (extraParams) {
state.queryParams = { itemid: extraParams.itemid || '', productid: extraParams.productid || '' };
state.page = 1;
} else {
state.page = pageNum;
}
const params = new URLSearchParams({
page: String(state.page),
rows: String(state.rows),
itemid: state.queryParams.itemid,
productid: state.queryParams.productid,
});
state.lastPayload = Object.fromEntries(params.entries());
const resp = await fetch('/datagrid24_getdata', { method: 'POST', body: params });
const json = await resp.json();
state.total = json.total;
state.data = json.rows;
const tbody = document.querySelector('#tt tbody');
tbody.innerHTML = '';
const offset = (state.page - 1) * state.rows;
json.rows.forEach((r, idx) => {
const tr = document.createElement('tr');
tr.innerHTML = `<td>${offset + idx + 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>`;
tbody.appendChild(tr);
});
document.getElementById('pager-info').textContent = `Page ${state.page} / Total ${state.total}`;
window._loadDone = (window._loadDone || 0) + 1;
}
window.doSearch = function() {
loadPage(1, {
itemid: document.getElementById('itemid').value,
productid: document.getElementById('productid').value,
});
};
document.getElementById('btn-prev').addEventListener('click', () => {
if (state.page > 1) loadPage(state.page - 1);
});
document.getElementById('btn-next').addEventListener('click', () => {
if (state.page * state.rows < state.total) loadPage(state.page + 1);
});
window.gridState = () => ({
page: state.page,
total: state.total,
rowNumbers: Array.from(document.querySelectorAll('#tt tbody tr td:first-child')).map(td => parseInt(td.textContent, 10)),
itemids: state.data.map(r => r.itemid),
lastPayload: state.lastPayload,
});
loadPage(1);
</script>
</body>
</html>
"""
def start_server():
conn = sqlite3.connect(":memory:", check_same_thread=False)
conn.execute("CREATE TABLE item (itemid TEXT, productid TEXT, listprice REAL, unitcost REAL, attr1 TEXT, status TEXT)")
conn.executemany("INSERT INTO item VALUES (?, ?, ?, ?, ?, ?)", SEED_ITEMS)
conn.commit()
lock = threading.Lock()
class Handler(BaseHTTPRequestHandler):
def log_message(self, fmt, *args):
pass
def do_GET(self):
body = HTML_DOC.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_POST(self):
length = int(self.headers.get("Content-Length", "0"))
raw = self.rfile.read(length).decode("utf-8")
qs = parse_qs(raw, keep_blank_values=True)
page = max(1, int(qs.get("page", ["1"])[0]))
rows = max(1, int(qs.get("rows", ["10"])[0]))
itemid = qs.get("itemid", [""])[0]
productid = qs.get("productid", [""])[0]
offset = (page - 1) * rows
with lock:
total = conn.execute(
"SELECT COUNT(*) FROM item WHERE itemid LIKE ? AND productid LIKE ?",
(itemid + "%", productid + "%"),
).fetchone()[0]
cur = conn.execute(
"SELECT itemid, productid, listprice, unitcost, attr1, status FROM item "
"WHERE itemid LIKE ? AND productid LIKE ? LIMIT ? OFFSET ?",
(itemid + "%", productid + "%", rows, offset),
)
items = [
dict(itemid=r[0], productid=r[1], listprice=r[2], unitcost=r[3], attr1=r[4], status=r[5])
for r in cur.fetchall()
]
payload = json.dumps({"total": total, "rows": items}).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
srv = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
t = threading.Thread(target=srv.serve_forever, daemon=True)
t.start()
return srv, conn
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main():
srv, conn = start_server()
port = srv.server_address[1]
cases = []
try:
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page(viewport={"width": 760, "height": 480})
page.goto(f"http://127.0.0.1:{port}/")
page.wait_for_function("() => window._loadDone >= 1")
# Case 1: Initial paginated load from loopback HTTP/SQLite endpoint
res1 = page.evaluate("() => window.gridState()")
exp1 = {
"page": 1,
"total": 12,
"rowNumbers": [1, 2, 3, 4, 5],
"itemids": ["EST-1", "EST-10", "EST-11", "EST-12", "EST-13"],
"lastPayload": {"page": "1", "rows": "5", "itemid": "", "productid": ""},
}
cases.append(dict(name="initial_paginated_load_from_loopback", expected=exp1, actual=res1, passed=(res1 == exp1)))
# Case 2: Toolbar search by itemid and productid prefix via doSearch -> load
page.fill("#itemid", "EST-1")
page.fill("#productid", "RP-SN")
page.click("#btn-search")
page.wait_for_function("() => window._loadDone >= 2")
res2 = page.evaluate("() => window.gridState()")
exp2 = {
"page": 1,
"total": 2,
"rowNumbers": [1, 2],
"itemids": ["EST-11", "EST-12"],
"lastPayload": {"page": "1", "rows": "5", "itemid": "EST-1", "productid": "RP-SN"},
}
cases.append(dict(name="toolbar_search_by_itemid_and_productid", expected=exp2, actual=res2, passed=(res2 == exp2)))
# Case 3: Reset inputs -> page 2 -> empty search resets page to 1
page.fill("#itemid", "")
page.fill("#productid", "")
page.click("#btn-search")
page.wait_for_function("() => window._loadDone >= 3")
page.click("#btn-next")
page.wait_for_function("() => window._loadDone >= 4")
page2_state = page.evaluate("() => ({ page: window.gridState().page, rowNumbers: window.gridState().rowNumbers })")
page.fill("#itemid", "NOPE")
page.click("#btn-search")
page.wait_for_function("() => window._loadDone >= 5")
empty_state = page.evaluate("() => window.gridState()")
res3 = {
"page2BeforeEmpty": page2_state,
"emptyPage": empty_state["page"],
"emptyTotal": empty_state["total"],
"emptyItemIds": empty_state["itemids"],
}
exp3 = {
"page2BeforeEmpty": {"page": 2, "rowNumbers": [6, 7, 8, 9, 10]},
"emptyPage": 1,
"emptyTotal": 0,
"emptyItemIds": [],
}
cases.append(dict(name="search_resets_page_and_handles_empty_match", expected=exp3, actual=res3, passed=(res3 == exp3)))
browser.close()
finally:
srv.shutdown()
conn.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对初始分页加载(total=12、行号 1..5)、组合前缀过滤(EST-1 + RP-SN 命中 2 条)以及翻页后执行空结果查询自动重置回第 1 页。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:9c8aeb6e6f6ac7c0ef35289644e780822efb2219e3dffb83b11a668f3103e853
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:ca8cc5e66a956b133710451aab2ad40374b1e09ce4199935a92d2dde29385156
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
执行关键词筛选时,为何推荐调用 `datagrid('load', params)` 而不是 `datagrid('reload', params)`?服务端实现 `LIKE` 查询时应如何替代历史 `mysql_real_escape_string`?
展开参考解答
`load` 会把页码重置为第 1 页再请求数据,避免用户停留在第 3 页而新筛选结果不足 3 页导致空白;`reload` 则保持当前页码。服务端应使用 PDO/MySQLi/SQLite 参数化查询绑定占位符(`?`)取代已废弃的 `mysql_*` 扩展。