jEasyUI 设置排序
核对 DataGrid 列 sortable="true" 启用点击表头远程排序、POST 提交 sort/order 参数,以及服务端白名单校验排序字段并配合分页返回的回环实测。
学完这一章,你能够
- 核对 DataGrid 列 sortable="true" 启用点击表头远程排序、POST 提交 sort/order 参数,以及服务端白名单校验排序字段并配合分页返回的回环实测。
启用表头排序与远程参数约定
DataGrid 支持点击表头触发数据排序,但默认全部列均不可排序,必须为允许排序的列显式声明 `sortable="true"`。
在网格表头中将 `itemid`、`productid`、`listprice`、`unitcost` 设为 `sortable="true"`,而 `attr1` 与 `status` 保持默认不可排序。每次点击可排序表头时,组件会向远程接口发送两个参数:`sort` 表示排序字段名,`order` 表示排序方向(`'asc'` 或 `'desc'`,默认 `'asc'`,再次点击同列则交替翻转)。
服务端排序查询安全实践与回环实测
服务端除读取 `page` 与 `rows` 外,还需提取 `sort`(默认 `'itemid'`)与 `order`(默认 `'asc'`)并拼接 `ORDER BY` 与分页 `LIMIT`。需特别注意:原始示例直接使用 PHP 废弃的 `mysql_query` 并将未校验的 `$sort`/`$order` 拼入 SQL,存在 SQL 注入风险;生产代码必须将排序列名限制在静态白名单内、将方向严格限定为 `asc`/`desc`。本站基于 `127.0.0.1` 回环 HTTP + SQLite 服务联调 Chromium 实测:首次点击 `listprice` 发送 `sort=listprice&order=asc` 返回 `[16.5, 18.5, 26.5, 28.5]`,再次点击翻转为 `desc` 返回 `[193.5, 58.5, 28.5, 26.5]`;点击不可排序的 `attr1`、`status` 请求次数保持 `3` 不变;按 `unitcost desc` 翻至第 2 页返回 `[11.0, 10.0]`,而传入非法排序串 `'listprice; DROP TABLE item'` 时白名单安全回退至 `itemid asc` 且数据表完好无损。
原始示例包 `jeasyui-datagrid-datagrid8.zip` 未发起网络下载并已登记于附件清单;运行本地回环实验脚本可离线验证排序切换、分页联动与白名单防护。
运行 DataGrid 表头远程排序、分页联动与白名单校验的回环实验
"""Offline Playwright Chromium + loopback HTTP/SQLite lab for jQuery EasyUI Ch 29: DataGrid Sorting."""
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", "P"),
("EST-11", "RP-SN-01", 28.5, 15.0, "Venomless", "P"),
("EST-12", "RP-SN-01", 26.5, 11.0, "Rattleless", "P"),
("EST-14", "FL-DSH-01", 58.5, 30.0, "Tailless", "P"),
("EST-18", "AV-CB-01", 193.5, 92.0, "Adult Male", "P"),
]
ALLOWED_SORT = {"itemid", "productid", "listprice", "unitcost"}
HTML_DOC = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>EasyUI DataGrid Server Sorting Offline Lab</title>
<style>
body { font-family: sans-serif; margin: 12px; }
.dg-panel { width: 620px; border: 1px solid #95b8e7; }
.dg-title { background: #e0ecff; padding: 6px 8px; font-weight: 600; font-size: 13px; border-bottom: 1px solid #95b8e7; }
table { width: 100%; border-collapse: collapse; font-size: 12px; }
th, td { border: 1px solid #ddd; padding: 4px 6px; }
th { background: #efefef; user-select: none; }
th[sortable="true"] { cursor: pointer; }
.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>
<table id="tt">
<thead>
<tr>
<th width="28">#</th>
<th field="itemid" width="80" sortable="true">Item ID</th>
<th field="productid" width="80" sortable="true">Product ID</th>
<th field="listprice" width="80" align="right" sortable="true">List Price</th>
<th field="unitcost" width="80" align="right" sortable="true">Unit Cost</th>
<th field="attr1" width="150">Attribute</th>
<th field="status" width="60" align="center">Status</th>
</tr>
</thead>
<tbody></tbody>
</table>
<div class="dg-pager">
<button id="btn-p1" type="button">Page 1</button>
<button id="btn-p2" type="button">Page 2</button>
<span id="pager-info"></span>
</div>
</div>
<script>
const state = { page: 1, rows: 4, sort: 'itemid', order: 'asc', requestCount: 0, lastPayload: null, data: [] };
async function fetchSorted(override) {
if (override) Object.assign(state, override);
const params = new URLSearchParams({
page: String(state.page),
rows: String(state.rows),
sort: state.sort,
order: state.order,
});
state.lastPayload = Object.fromEntries(params.entries());
state.requestCount += 1;
const resp = await fetch('/datagrid8_getdata', { method: 'POST', body: params });
const json = await resp.json();
state.data = json.rows;
state.appliedSort = json.appliedSort;
state.appliedOrder = json.appliedOrder;
const tbody = document.querySelector('#tt tbody');
const offset = (state.page - 1) * state.rows;
tbody.innerHTML = json.rows.map((r, i) =>
`<tr><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('');
document.getElementById('pager-info').textContent = `Page ${state.page} | sort=${json.appliedSort} ${json.appliedOrder}`;
window._doneCount = state.requestCount;
}
document.querySelectorAll('#tt thead th').forEach(th => {
th.addEventListener('click', () => {
if (th.getAttribute('sortable') !== 'true') return;
const field = th.getAttribute('field');
const nextOrder = (state.sort === field && state.order === 'asc') ? 'desc' : 'asc';
fetchSorted({ sort: field, order: nextOrder, page: 1 });
});
});
document.getElementById('btn-p1').addEventListener('click', () => fetchSorted({ page: 1 }));
document.getElementById('btn-p2').addEventListener('click', () => fetchSorted({ page: 2 }));
window.directSortRequest = (sort, order, page) => fetchSorted({ sort, order, page });
window.sortSnapshot = () => ({
requestCount: state.requestCount,
lastPayload: state.lastPayload,
appliedSort: state.appliedSort,
appliedOrder: state.appliedOrder,
itemids: state.data.map(r => r.itemid),
listprices: state.data.map(r => r.listprice),
unitcosts: state.data.map(r => r.unitcost),
});
fetchSorted();
</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]))
req_sort = qs.get("sort", ["itemid"])[0]
req_order = qs.get("order", ["asc"])[0].lower()
sort = req_sort if req_sort in ALLOWED_SORT else "itemid"
order = "desc" if req_order == "desc" else "asc"
if req_sort not in ALLOWED_SORT:
order = "asc"
offset = (page - 1) * rows
with lock:
total = conn.execute("SELECT COUNT(*) FROM item").fetchone()[0]
cur = conn.execute(
f"SELECT itemid, productid, listprice, unitcost, attr1, status FROM item ORDER BY {sort} {order} LIMIT ? OFFSET ?",
(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, "appliedSort": sort, "appliedOrder": order}).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": 740, "height": 460})
page.goto(f"http://127.0.0.1:{port}/")
page.wait_for_function("() => window._doneCount >= 1")
# Case 1: Click sortable listprice header -> asc then desc
page.click('th[field="listprice"]')
page.wait_for_function("() => window._doneCount >= 2")
asc_snap = page.evaluate("() => window.sortSnapshot()")
page.click('th[field="listprice"]')
page.wait_for_function("() => window._doneCount >= 3")
desc_snap = page.evaluate("() => window.sortSnapshot()")
res1 = {
"ascPayload": asc_snap["lastPayload"],
"ascPrices": asc_snap["listprices"],
"descPayload": desc_snap["lastPayload"],
"descPrices": desc_snap["listprices"],
}
exp1 = {
"ascPayload": {"page": "1", "rows": "4", "sort": "listprice", "order": "asc"},
"ascPrices": [16.5, 18.5, 26.5, 28.5],
"descPayload": {"page": "1", "rows": "4", "sort": "listprice", "order": "desc"},
"descPrices": [193.5, 58.5, 28.5, 26.5],
}
cases.append(dict(name="sortable_header_click_asc_then_desc", expected=exp1, actual=res1, passed=(res1 == exp1)))
# Case 2: Non-sortable columns attr1 and status ignore clicks
before_cnt = page.evaluate("() => window.sortSnapshot().requestCount")
page.click('th[field="attr1"]')
page.click('th[field="status"]')
after_snap = page.evaluate("() => window.sortSnapshot()")
res2 = {
"beforeCount": before_cnt,
"afterCount": after_snap["requestCount"],
"sortUnchanged": after_snap["appliedSort"] == "listprice" and after_snap["appliedOrder"] == "desc",
}
exp2 = {"beforeCount": 3, "afterCount": 3, "sortUnchanged": True}
cases.append(dict(name="non_sortable_columns_ignore_clicks", expected=exp2, actual=res2, passed=(res2 == exp2)))
# Case 3: Paginated unitcost desc + server whitelist fallback against invalid sort key
page.click('th[field="unitcost"]')
page.wait_for_function("() => window._doneCount >= 4")
page.click('th[field="unitcost"]')
page.wait_for_function("() => window._doneCount >= 5")
page.click("#btn-p2")
page.wait_for_function("() => window._doneCount >= 6")
p2_snap = page.evaluate("() => window.sortSnapshot()")
page.evaluate("() => window.directSortRequest('listprice; DROP TABLE item', 'desc', 1)")
page.wait_for_function("() => window._doneCount >= 7")
safe_snap = page.evaluate("() => window.sortSnapshot()")
res3 = {
"page2Payload": p2_snap["lastPayload"],
"page2UnitCosts": p2_snap["unitcosts"],
"invalidSortFallback": {"appliedSort": safe_snap["appliedSort"], "appliedOrder": safe_snap["appliedOrder"]},
"tableIntactCount": len(safe_snap["itemids"]),
}
exp3 = {
"page2Payload": {"page": "2", "rows": "4", "sort": "unitcost", "order": "desc"},
"page2UnitCosts": [11.0, 10.0],
"invalidSortFallback": {"appliedSort": "itemid", "appliedOrder": "asc"},
"tableIntactCount": 4,
}
cases.append(dict(name="server_whitelist_and_pagination_with_sort", 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()
- 核对 listprice 升序/降序切换、非排序列忽略点击、unitcost desc 第 2 页数据,以及非法 sort 字段被服务端白名单安全回退至 itemid asc。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:4218b26b92075d01ed00a22fb23d082400aa8110fb06d28d728110e01fdf20cd
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:6c945f3d9194b783ac4e7f4e539c19b1d97ddbd647582b95b5f15730850fa6f0
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在服务端处理 DataGrid 传来的 `sort` 和 `order` 参数时,为何不能仅依赖参数化占位符处理 `ORDER BY`?正确的安全写法是什么?
展开参考解答
SQL 参数化占位符只能绑定字面量值,不能绑定列名或 `ASC`/`DESC` 关键字;因此必须维护允许排序的列名白名单集合,仅当请求值命中白名单时才拼入 `ORDER BY`,否则回退到安全默认列。