jEasyUI 过滤下拉数据网格
核对 ComboGrid 的 idField/textField 绑定、多列表头配置及 remote(发送 q 参数)与 local 两种记录过滤模式的 Chromium 实测。
学完这一章,你能够
- 核对 ComboGrid 的 idField/textField 绑定、多列表头配置及 remote(发送 q 参数)与 local 两种记录过滤模式的 Chromium 实测。
ComboGrid 架构与核心属性配置
下拉数据网格(ComboGrid)将下拉框的输入交互与数据网格(DataGrid)的多列展示、过滤和分页能力结合在一起。初始化 `$('#cg').combogrid({...})` 时需配置面板宽度 `panelWidth: 500`、列定义 `columns`(`itemid`、`productid`、`listprice`、`unitcost`、`attr1`、`status`)、`fitColumns: true`,以及成对关键属性 `idField`(存储组件提交值)与 `textField`(在文本框中显示给用户的文本)。
remote / local 过滤模式与离线实测
ComboGrid 支持 `local` 本地内存过滤与 `remote` 远程服务端过滤两种 `mode`:设为 `mode: 'remote'` 后,用户键入关键字时组件会向后端 `form5_getdata.php` 发送参数 `q`,由服务端按 `itemid` 或 `productid` 模糊匹配返回筛选后的 JSON 行数组(原 PHP 片段直接拼接 `like '%$q%'` 存在 SQL 注入风险,实际开发必须改用参数化查询)。
本站通过本地回环 `/form5_getdata` 接口实测 6 条商品明细:初始加载呈现 6 列宽 500px 面板,点选 `EST-10` 后 `getValue()` 返回 `"EST-10"`(`idField`)、`getText()` 返回 `"K9-DL-01"`(`textField`);在 `remote` 模式下输入 `"FI-SW"` 触发 POST `q="FI-SW"`,列表精确缩减为 `['EST-1', 'EST-2']`;切换至 `local` 模式并检索 `"RP-SN"` 时,本地内存即时过滤出 `['EST-11', 'EST-12']` 且产生 `0` 次额外网络请求。原压缩包未下载。
运行下拉数据网格选行绑定与 remote/local 双模式过滤实验
展开查看收起
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 66 (form-form5): Filterable ComboGrid."""
import json
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs
from playwright.sync_api import sync_playwright
ITEMS_DB = [
{"itemid": "EST-1", "productid": "FI-SW-01", "listprice": 16.50, "unitcost": 10.00, "attr1": "Large", "status": "P"},
{"itemid": "EST-10", "productid": "K9-DL-01", "listprice": 18.50, "unitcost": 12.00, "attr1": "Spotted Adult Female", "status": "P"},
{"itemid": "EST-11", "productid": "RP-SN-01", "listprice": 18.50, "unitcost": 12.00, "attr1": "Venomless", "status": "P"},
{"itemid": "EST-12", "productid": "RP-SN-01", "listprice": 18.50, "unitcost": 12.00, "attr1": "Rattleless", "status": "P"},
{"itemid": "EST-13", "productid": "RP-LI-02", "listprice": 18.50, "unitcost": 12.00, "attr1": "Green Adult", "status": "P"},
{"itemid": "EST-2", "productid": "FI-SW-01", "listprice": 16.50, "unitcost": 10.00, "attr1": "Small", "status": "P"},
]
def start_server():
query_log = []
class Handler(BaseHTTPRequestHandler):
def log_message(self, fmt, *args):
pass
def do_GET(self):
if self.path == "/":
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)
else:
self.send_response(404)
self.end_headers()
def do_POST(self):
if self.path == "/form5_getdata":
length = int(self.headers.get("Content-Length", "0"))
params = parse_qs(self.rfile.read(length).decode("utf-8"), keep_blank_values=True)
q = params.get("q", [""])[0]
query_log.append(q)
ql = q.lower()
rows = [
r for r in ITEMS_DB
if ql in r["itemid"].lower() or ql in r["productid"].lower()
]
body = json.dumps(rows).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
else:
self.send_response(404)
self.end_headers()
srv = HTTPServer(("127.0.0.1", 0), Handler)
t = threading.Thread(target=srv.serve_forever, daemon=True)
t.start()
return srv, srv.server_address[1], query_log
HTML_DOC = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>jQuery EasyUI Filterable ComboGrid Offline Lab</title>
<style>
#cg-panel { border: 1px solid #94a3b8; margin-top: 4px; }
table { border-collapse: collapse; width: 100%; font-family: sans-serif; font-size: 12px; }
th, td { border: 1px solid #cbd5e1; padding: 3px 6px; }
tr.cg-selected { background: #fde68a; }
</style>
</head>
<body>
<input id="cg" style="width:150px">
<div id="cg-panel">
<table id="cg-table">
<thead id="cg-head"></thead>
<tbody id="cg-body"></tbody>
</table>
</div>
<script>
(function () {
const inp = document.getElementById('cg');
const panel = document.getElementById('cg-panel');
const thead = document.getElementById('cg-head');
const tbody = document.getElementById('cg-body');
let opts = null;
let allRows = [];
let visibleRows = [];
let selectedVal = '';
async function fetchRemote(q) {
const resp = await fetch(opts.url, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: 'q=' + encodeURIComponent(q)
});
return resp.json();
}
function renderRows(rows) {
visibleRows = rows;
tbody.innerHTML = '';
for (const r of rows) {
const tr = document.createElement('tr');
tr.dataset.id = String(r[opts.idField]);
if (selectedVal === r[opts.idField]) tr.classList.add('cg-selected');
tr.innerHTML = opts.columns[0].map(c => `<td style="text-align:${c.align || 'left'}">${r[c.field]}</td>`).join('');
tr.addEventListener('click', () => {
selectedVal = r[opts.idField];
inp.value = r[opts.textField];
renderRows(visibleRows);
});
tbody.appendChild(tr);
}
}
async function filterQuery(q) {
if (opts.mode === 'remote') {
const rows = await fetchRemote(q);
renderRows(rows);
} else {
const ql = q.toLowerCase();
const filtered = allRows.filter(r =>
String(r[opts.idField]).toLowerCase().includes(ql) ||
String(r[opts.textField]).toLowerCase().includes(ql)
);
renderRows(filtered);
}
}
window.$ = (sel) => ({
combogrid: (arg1, arg2) => {
if (typeof arg1 === 'object') {
opts = arg1;
panel.style.width = opts.panelWidth + 'px';
thead.innerHTML = '<tr>' + opts.columns[0].map(c => `<th>${c.title}</th>`).join('') + '</tr>';
return fetchRemote('').then(rows => {
allRows = rows;
renderRows(rows);
});
}
if (arg1 === 'getValue') return selectedVal;
if (arg1 === 'getText') return inp.value;
if (arg1 === 'setMode') { opts.mode = arg2; return; }
}
});
window.__filterQuery = filterQuery;
window.__visibleIds = () => visibleRows.map(r => r.itemid);
window.__ready = $('#cg').combogrid({
panelWidth: 500,
url: '/form5_getdata',
idField: 'itemid',
textField: 'productid',
mode: 'remote',
fitColumns: true,
columns: [[
{ field: 'itemid', title: 'Item ID', width: 60 },
{ field: 'productid', title: 'Product ID', align: 'right', width: 80 },
{ field: 'listprice', title: 'List Price', align: 'right', width: 60 },
{ field: 'unitcost', title: 'Unit Cost', align: 'right', width: 60 },
{ field: 'attr1', title: 'Attribute', width: 150 },
{ field: 'status', title: 'Status', align: 'center', width: 60 }
]]
});
})();
</script>
</body>
</html>
"""
def launch_browser(pw):
try:
return pw.chromium.launch(headless=True)
except Exception:
return pw.chromium.launch(headless=True, channel="chrome")
def main():
srv, port, query_log = start_server()
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.evaluate("() => window.__ready")
# Case 1: Initial load renders 6 columns & 6 rows; selecting a row binds idField vs textField
page.click('#cg-body tr[data-id="EST-10"]')
res1 = page.evaluate("""() => ({
panel_width: document.getElementById('cg-panel').style.width,
col_count: document.querySelectorAll('#cg-head th').length,
initial_rows: window.__visibleIds().length,
value_idField: $('#cg').combogrid('getValue'),
text_textField: $('#cg').combogrid('getText')
})""")
exp1 = {
"panel_width": "500px",
"col_count": 6,
"initial_rows": 6,
"value_idField": "EST-10",
"text_textField": "K9-DL-01",
}
cases.append({
"name": "combogrid_columns_and_idfield_textfield_binding",
"passed": res1 == exp1,
"expected": exp1,
"actual": res1,
})
# Case 2: Remote mode sends POST q="FI-SW" and narrows dropdown grid to matching records
r2 = page.evaluate("""async () => {
await window.__filterQuery('FI-SW');
return { matched_ids: window.__visibleIds() };
}""")
act2 = {**r2, "query_log": list(query_log)}
exp2 = {"matched_ids": ["EST-1", "EST-2"], "query_log": ["", "FI-SW"]}
cases.append({
"name": "combogrid_remote_mode_sends_q_filter",
"passed": act2 == exp2,
"expected": exp2,
"actual": act2,
})
# Case 3: Switching to local mode filters cached rows in memory with zero additional POSTs
before = len(query_log)
r3 = page.evaluate("""async () => {
$('#cg').combogrid('setMode', 'local');
await window.__filterQuery('RP-SN');
return { local_matched_ids: window.__visibleIds() };
}""")
act3 = {**r3, "extra_remote_posts": len(query_log) - before}
exp3 = {"local_matched_ids": ["EST-11", "EST-12"], "extra_remote_posts": 0}
cases.append({
"name": "combogrid_local_mode_filters_without_network",
"passed": act3 == exp3,
"expected": exp3,
"actual": act3,
})
browser.close()
finally:
srv.shutdown()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
`local` 适合数据量较小(数百行内)的静态选项,过滤无延迟且不发额外请求;`remote` 适合候选记录庞大的业务数据,每次输入借由 `q` 参数交由服务端分页筛选返回。