"""Offline Playwright Chromium lab for jQuery UI Ch 23: Autocomplete (with local 127.0.0.1 HTTP server)."""
import http.server
import json
import threading
import urllib.parse
from playwright.sync_api import sync_playwright
BIRDS = [
{"id": "Haliaeetus leucocephalus", "label": "Bald Eagle", "value": "Bald Eagle"},
{"id": "Aquila chrysaetos", "label": "Golden Eagle", "value": "Golden Eagle"},
{"id": "Passer domesticus", "label": "House Sparrow", "value": "House Sparrow"},
{"id": "Spizella passerina", "label": "Chipping Sparrow", "value": "Chipping Sparrow"},
{"id": "Falco peregrinus", "label": "Peregrine Falcon", "value": "Peregrine Falcon"},
]
LONDON_XML = """<?xml version="1.0" encoding="UTF-8"?>
<geonames>
<geoname><name>London</name><countryName>United Kingdom</countryName><geonameId>2643743</geonameId></geoname>
<geoname><name>London</name><countryName>Canada</countryName><geonameId>6058560</geonameId></geoname>
<geoname><name>East London</name><countryName></countryName><geonameId>1006984</geonameId></geoname>
</geonames>
"""
HTML_DOC = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Autocomplete Offline Lab</title>
<style>
body { font-family: sans-serif; margin: 12px; }
.ui-autocomplete { list-style: none; margin: 0; padding: 0; border: 1px solid #999; width: 220px; }
.ui-autocomplete li { padding: 4px 6px; }
.ui-autocomplete-category { font-weight: bold; background: #eee; }
#scroll-menu { max-height: 100px; overflow-y: auto; overflow-x: hidden; }
</style>
</head>
<body>
<input id="tags"><ul id="tags-menu" class="ui-autocomplete"></ul>
<input id="developer"><ul id="dev-menu" class="ui-autocomplete"></ul>
<input id="cat-search"><ul id="cat-menu" class="ui-autocomplete"></ul>
<input id="project"><input type="hidden" id="project-id"><img id="project-icon" src=""><p id="project-desc"></p>
<select id="combobox-select">
<option value="">请选择...</option>
<option value="Java">Java</option>
<option value="JavaScript">JavaScript</option>
<option value="Python">Python</option>
<option value="Ruby">Ruby</option>
</select>
<input id="combobox-input" title="">
<ul id="scroll-menu" class="ui-autocomplete"></ul>
<input id="multi-local">
<input id="multi-remote">
<input id="remote-cache">
<input id="jsonp-input">
<div id="xml-log"></div>
<script>
const TAGS = [
"ActionScript","AppleScript","Asp","BASIC","C","C++","Clojure","COBOL","ColdFusion",
"Erlang","Fortran","Groovy","Haskell","Java","JavaScript","Lisp","Perl","PHP",
"Python","Ruby","Scala","Scheme"
];
const NAMES = ["Jörn Zaefferer", "Scott González", "John Resig"];
const ACCENT_MAP = { "á": "a", "ö": "o" };
function normalizeAccent(term) {
let out = "";
for (let i = 0; i < term.length; i++) out += ACCENT_MAP[term.charAt(i)] || term.charAt(i);
return out;
}
function escapeRegex(s) { return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); }
function filterTags(arr, term) {
const re = new RegExp(escapeRegex(term), "i");
return arr.filter(v => re.test(v));
}
window.AcLab = {
searchDefault(term) {
return filterTags(TAGS, term);
},
searchAccent(term) {
const re = new RegExp(escapeRegex(term), "i");
return NAMES.filter(v => re.test(v) || re.test(normalizeAccent(v)));
},
renderCategorized(term) {
const data = [
{ label: "anders", category: "" },
{ label: "andreas", category: "" },
{ label: "antal", category: "" },
{ label: "annhhx10", category: "Products" },
{ label: "annk K12", category: "Products" },
{ label: "annttop C13", category: "Products" },
{ label: "anders andersson", category: "People" },
{ label: "andreas andersson", category: "People" },
{ label: "andreas johnson", category: "People" }
];
const re = new RegExp(escapeRegex(term), "i");
const items = data.filter(d => re.test(d.label));
const ul = document.getElementById("cat-menu");
ul.innerHTML = "";
let cur = "";
items.forEach(item => {
if (item.category !== cur) {
const h = document.createElement("li");
h.className = "ui-autocomplete-category";
h.textContent = item.category;
ul.appendChild(h);
cur = item.category;
}
const li = document.createElement("li");
li.textContent = item.label;
ul.appendChild(li);
});
return {
categories: Array.from(ul.querySelectorAll(".ui-autocomplete-category")).map(n => n.textContent),
itemCount: items.length
};
},
selectCustomProject(term) {
const projects = [
{ value: "jquery", label: "jQuery", desc: "the write less, do more, JavaScript library", icon: "jquery_32x32.png" },
{ value: "jquery-ui", label: "jQuery UI", desc: "the official user interface library for jQuery", icon: "jqueryui_32x32.png" },
{ value: "sizzlejs", label: "Sizzle JS", desc: "a pure-JavaScript CSS selector engine", icon: "sizzlejs_32x32.png" }
];
const re = new RegExp(escapeRegex(term), "i");
const matched = projects.filter(p => re.test(p.label));
const chosen = matched[1];
document.getElementById("project").value = chosen.label;
document.getElementById("project-id").value = chosen.value;
document.getElementById("project-desc").textContent = chosen.desc;
document.getElementById("project-icon").setAttribute("src", "images/" + chosen.icon);
return {
matchedCount: matched.length,
label: document.getElementById("project").value,
id: document.getElementById("project-id").value,
desc: document.getElementById("project-desc").textContent,
icon: document.getElementById("project-icon").getAttribute("src")
};
},
testComboboxAndScroll() {
const sel = document.getElementById("combobox-select");
const inp = document.getElementById("combobox-input");
const allOpts = Array.from(sel.options).filter(o => o.value).map(o => o.textContent);
// Select Python
inp.value = "Python";
Array.from(sel.options).forEach(o => { o.selected = (o.textContent === "Python"); });
const syncedValue = sel.value;
// Invalid input removed on blur
inp.value = "NoSuchLang";
const valid = Array.from(sel.options).some(o => o.value && o.textContent.toLowerCase() === inp.value.toLowerCase());
if (!valid) {
inp.title = inp.value + " didn't match any item";
inp.value = "";
sel.value = "";
}
// Scrollable menu for "a"
const ul = document.getElementById("scroll-menu");
ul.innerHTML = "";
filterTags(TAGS, "a").forEach(t => {
const li = document.createElement("li");
li.textContent = t;
ul.appendChild(li);
});
return {
allOptCount: allOpts.length,
syncedValue,
clearedValue: inp.value,
errorTitle: inp.title,
scrollOverflows: ul.scrollHeight > ul.clientHeight
};
},
testMultiLocal() {
const split = v => v.split(/,\s*/);
const extractLast = v => split(v).pop();
const inp = document.getElementById("multi-local");
inp.value = "ja";
const firstCandidates = filterTags(TAGS, extractLast(inp.value));
let terms = split(inp.value); terms.pop(); terms.push(firstCandidates[0]); terms.push("");
inp.value = terms.join(", ");
inp.value += "py";
const secondCandidates = filterTags(TAGS, extractLast(inp.value));
terms = split(inp.value); terms.pop(); terms.push(secondCandidates[0]); terms.push("");
inp.value = terms.join(", ");
return { firstCandidates, secondCandidates, finalValue: inp.value };
},
async testMultiRemote() {
const split = v => v.split(/,\s*/);
const extractLast = v => split(v).pop();
const inp = document.getElementById("multi-remote");
// minLength 2 guard: 1 char does not fetch
inp.value = "e";
let skippedShort = extractLast(inp.value).length < 2;
inp.value = "ea";
const r1 = await fetch("/search.php?term=" + encodeURIComponent(extractLast(inp.value))).then(r => r.json());
let terms = split(inp.value); terms.pop(); terms.push(r1[0].value); terms.push("");
inp.value = terms.join(", ");
inp.value += "go";
const r2 = await fetch("/search.php?term=" + encodeURIComponent(extractLast(inp.value))).then(r => r.json());
terms = split(inp.value); terms.pop(); terms.push(r2[0].value); terms.push("");
inp.value = terms.join(", ");
return { skippedShort, firstCount: r1.length, finalValue: inp.value };
},
async testCacheJsonpXml() {
const cache = {};
async function cachedQuery(term) {
if (term in cache) return { fromCache: true, items: cache[term] };
const data = await fetch("/search.php?term=" + encodeURIComponent(term)).then(r => r.json());
cache[term] = data;
return { fromCache: false, items: data };
}
const q1 = await cachedQuery("sp");
const q2 = await cachedQuery("sp");
// JSONP script tag
const jsonpItems = await new Promise(resolve => {
window.__jsonpCb = data => resolve(data);
const s = document.createElement("script");
s.src = "/search.php?term=fa&callback=__jsonpCb";
document.head.appendChild(s);
});
// XML parsing
const xmlText = await fetch("/london.xml").then(r => r.text());
const xmlDoc = new DOMParser().parseFromString(xmlText, "application/xml");
const geo = Array.from(xmlDoc.querySelectorAll("geoname")).map(node => ({
value: node.querySelector("name").textContent + ", " + (node.querySelector("countryName").textContent.trim() || "(unknown country)"),
id: node.querySelector("geonameId").textContent
}));
return {
q1FromCache: q1.fromCache,
q2FromCache: q2.fromCache,
spCount: q2.items.length,
jsonpFirst: jsonpItems[0].value,
xmlMapped: geo
};
}
};
</script>
</body>
</html>
"""
def main():
hit_counts = {"sp": 0, "ea": 0, "go": 0, "fa": 0, "xml": 0}
class Handler(http.server.BaseHTTPRequestHandler):
def log_message(self, format, *args):
pass
def do_GET(self):
parsed = urllib.parse.urlparse(self.path)
if parsed.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)
elif parsed.path == "/search.php":
qs = urllib.parse.parse_qs(parsed.query)
term = qs.get("term", [""])[0].lower()
if term in hit_counts:
hit_counts[term] += 1
matches = [b for b in BIRDS if term in b["label"].lower()]
payload = json.dumps(matches)
cb = qs.get("callback", [None])[0]
if cb:
body = f"{cb}({payload});".encode("utf-8")
ctype = "application/javascript; charset=utf-8"
else:
body = payload.encode("utf-8")
ctype = "application/json; charset=utf-8"
self.send_response(200)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
elif parsed.path == "/london.xml":
hit_counts["xml"] += 1
body = LONDON_XML.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/xml; 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()
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
cases = []
try:
with sync_playwright() as p:
try:
browser = p.chromium.launch(headless=True)
except Exception:
browser = p.chromium.launch(headless=True, channel="chrome")
page = browser.new_page()
page.goto(f"http://127.0.0.1:{port}/")
# Case 1: Default array + accent folding
res1 = page.evaluate("""() => ({
ja: AcLab.searchDefault("ja"),
jo: AcLab.searchAccent("Jo"),
joUmlaut: AcLab.searchAccent("Jö")
})""")
exp1 = {
"ja": ["Java", "JavaScript"],
"jo": ["Jörn Zaefferer", "John Resig"],
"joUmlaut": ["Jörn Zaefferer"],
}
cases.append(dict(name="autocomplete_default_and_accent_folding", expected=exp1, actual=res1, passed=(res1 == exp1)))
# Case 2: Categorized menu + custom data project selection
res2 = page.evaluate("""() => ({
cat: AcLab.renderCategorized("a"),
proj: AcLab.selectCustomProject("j")
})""")
exp2 = {
"cat": {"categories": ["Products", "People"], "itemCount": 9},
"proj": {
"matchedCount": 3,
"label": "jQuery UI",
"id": "jquery-ui",
"desc": "the official user interface library for jQuery",
"icon": "images/jqueryui_32x32.png",
},
}
cases.append(dict(name="autocomplete_categories_and_custom_data", expected=exp2, actual=res2, passed=(res2 == exp2)))
# Case 3: Combobox select sync/clear + scrollable max-height menu
res3 = page.evaluate("() => AcLab.testComboboxAndScroll()")
exp3 = {
"allOptCount": 4,
"syncedValue": "Python",
"clearedValue": "",
"errorTitle": "NoSuchLang didn't match any item",
"scrollOverflows": True,
}
cases.append(dict(name="autocomplete_combobox_and_scrollable", expected=exp3, actual=res3, passed=(res3 == exp3)))
# Case 4: Multi-value local + multi-value remote via loopback /search.php
res4 = page.evaluate("""async () => ({
local: AcLab.testMultiLocal(),
remote: await AcLab.testMultiRemote()
})""")
exp4 = {
"local": {
"firstCandidates": ["Java", "JavaScript"],
"secondCandidates": ["Python"],
"finalValue": "Java, Python, ",
},
"remote": {
"skippedShort": True,
"firstCount": 2,
"finalValue": "Bald Eagle, Golden Eagle, ",
},
}
cases.append(dict(name="autocomplete_multiple_local_and_remote", expected=exp4, actual=res4, passed=(res4 == exp4)))
# Case 5: Remote cache hit count, JSONP callback, XML parsing
res5 = page.evaluate("async () => await AcLab.testCacheJsonpXml()")
res5["serverSpHits"] = hit_counts["sp"]
exp5 = {
"q1FromCache": False,
"q2FromCache": True,
"spCount": 2,
"jsonpFirst": "Peregrine Falcon",
"xmlMapped": [
{"value": "London, United Kingdom", "id": "2643743"},
{"value": "London, Canada", "id": "6058560"},
{"value": "East London, (unknown country)", "id": "1006984"},
],
"serverSpHits": 1,
}
cases.append(dict(name="autocomplete_remote_cache_jsonp_xml", expected=exp5, actual=res5, passed=(res5 == exp5)))
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/jqueryui-example-autocomplete-lab/explore-example-autocomplete.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-example-autocomplete.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a922.zip
课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a916.zip