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