蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

通过本地 127.0.0.1 回环服务与离线 Chromium 实测 AJAX 无刷新局部更新及多格式数据交换

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-ajax-intro.py
explore-ajax-intro.py228 行
"""Offline Playwright Chromium lab for jQuery Chapter 26 (ajax-intro)."""
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs
from playwright.sync_api import sync_playwright

INDEX_HTML = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>jQuery AJAX Intro Lab</title></head>
<body>
  <div id="div1"><h2>使用 jQuery AJAX 修改文本内容</h2></div>
  <button id="btn1" type="button">获取外部内容</button>
  <div id="post-box">等待提交</div>
  <script>
    window.__pageToken = "stay-alive-token-26";
    (function (global) {
      function ajax(opts) {
        return new Promise((resolve, reject) => {
          const xhr = new XMLHttpRequest();
          const method = (opts.method || "GET").toUpperCase();
          xhr.open(method, opts.url, true);
          if (opts.contentType) xhr.setRequestHeader("Content-Type", opts.contentType);
          xhr.onload = function () {
            const ok = xhr.status >= 200 && xhr.status < 300;
            let data = xhr.responseText;
            if (ok && opts.dataType === "json") data = JSON.parse(data);
            if (ok && opts.dataType === "xml") data = new DOMParser().parseFromString(data, "application/xml");
            resolve({ ok, status: xhr.status, statusText: xhr.statusText, data, raw: xhr.responseText });
          };
          xhr.onerror = () => reject(new Error("network_error"));
          xhr.send(opts.body || null);
        });
      }
      function wrap(nodes) {
        const list = Array.from(nodes);
        return {
          click(fn) {
            for (const el of list) el.addEventListener("click", fn);
            return this;
          },
          load(url, cb) {
            ajax({ method: "GET", url }).then(res => {
              if (res.ok) {
                for (const el of list) el.innerHTML = res.raw;
              }
              if (cb) cb(res.raw, res.ok ? "success" : "error", res);
            });
            return this;
          }
        };
      }
      function $(arg) {
        if (arg === document) return { ready(fn) { fn(); } };
        if (typeof arg === "string") return wrap(document.querySelectorAll(arg));
        return wrap([]);
      }
      $.get = (url, dataType) => ajax({ method: "GET", url, dataType });
      $.post = (url, payload) => {
        const body = new URLSearchParams(payload).toString();
        return ajax({
          method: "POST",
          url,
          contentType: "application/x-www-form-urlencoded; charset=UTF-8",
          body
        });
      };
      global.$ = $;
    })(window);

    $(document).ready(function () {
      $("#btn1").click(function () {
        $("#div1").load("/demo_test.txt", function () {
          document.getElementById("div1").dataset.loaded = "yes";
        });
      });
    });
  </script>
</body>
</html>
"""


def start_server(state):
    class Handler(BaseHTTPRequestHandler):
        def log_message(self, format, *args):
            pass

        def _send(self, code, content_type, body):
            data = body.encode("utf-8")
            self.send_response(code)
            self.send_header("Content-Type", content_type)
            self.send_header("Content-Length", str(len(data)))
            self.end_headers()
            self.wfile.write(data)

        def do_GET(self):
            state["requests"].append(("GET", self.path))
            if self.path == "/":
                self._send(200, "text/html; charset=utf-8", INDEX_HTML)
            elif self.path == "/demo_test.txt":
                self._send(200, "text/plain; charset=utf-8", "<h2>外部文本已载入</h2><p id=\"p1\">局部更新成功,页面未重载。</p>")
            elif self.path == "/api/sample.html":
                self._send(200, "text/html; charset=utf-8", "<span class=\"badge\">HTML片段</span>")
            elif self.path == "/api/sample.json":
                self._send(200, "application/json; charset=utf-8", json.dumps({"mode": "json", "items": 3}))
            elif self.path == "/api/sample.xml":
                self._send(200, "application/xml; charset=utf-8", "<note><to>Client</to><msg>XML_OK</msg></note>")
            else:
                self._send(404, "text/plain; charset=utf-8", "Not Found")

        def do_POST(self):
            state["requests"].append(("POST", self.path))
            length = int(self.headers.get("Content-Length", "0"))
            raw = self.rfile.read(length).decode("utf-8")
            params = {k: v[0] for k, v in parse_qs(raw).items()}
            if self.path == "/api/echo":
                self._send(200, "application/json; charset=utf-8", json.dumps({"received": params}, ensure_ascii=False))
            else:
                self._send(404, "text/plain; charset=utf-8", "Not Found")

    server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()
    return server


def launch_browser(pw):
    try:
        return pw.chromium.launch(headless=True)
    except Exception:
        return pw.chromium.launch(headless=True, channel="chrome")


def main():
    state = {"requests": []}
    server = start_server(state)
    base_url = f"http://127.0.0.1:{server.server_port}"
    cases = []
    try:
        with sync_playwright() as p:
            browser = launch_browser(p)
            try:
                page = browser.new_page(viewport={"width": 1000, "height": 700})
                page.goto(base_url + "/")

                before_heading = page.locator("#div1 h2").text_content()
                page.click("#btn1")
                page.wait_for_selector("#div1[data-loaded='yes']")
                c1 = page.evaluate("""() => ({
                    after_h2: document.querySelector("#div1 h2").textContent,
                    after_p1: document.querySelector("#div1 #p1").textContent,
                    token_preserved: window.__pageToken === "stay-alive-token-26"
                })""")
                c1["before_h2"] = before_heading
                exp1 = {
                    "before_h2": "使用 jQuery AJAX 修改文本内容",
                    "after_h2": "外部文本已载入",
                    "after_p1": "局部更新成功,页面未重载。",
                    "token_preserved": True,
                }
                cases.append({"name": "ajax_partial_dom_update_no_reload", "passed": c1 == exp1, "expected": exp1, "actual": c1})

                c2 = page.evaluate("""async () => {
                    const rText = await $.get("/demo_test.txt", "text");
                    const rHtml = await $.get("/api/sample.html", "text");
                    const rJson = await $.get("/api/sample.json", "json");
                    const rXml = await $.get("/api/sample.xml", "xml");
                    return {
                        text_status: rText.status,
                        html_fragment: rHtml.data,
                        json_mode: rJson.data.mode,
                        json_items: rJson.data.items,
                        xml_msg: rXml.data.querySelector("msg").textContent
                    };
                }""")
                exp2 = {
                    "text_status": 200,
                    "html_fragment": '<span class="badge">HTML片段</span>',
                    "json_mode": "json",
                    "json_items": 3,
                    "xml_msg": "XML_OK",
                }
                cases.append({"name": "ajax_multi_format_get_requests", "passed": c2 == exp2, "expected": exp2, "actual": c2})

                c3 = page.evaluate("""async () => {
                    const res = await $.post("/api/echo", { action: "sync", channel: "ajax" });
                    const parsed = JSON.parse(res.data);
                    document.getElementById("post-box").textContent = parsed.received.action + ":" + parsed.received.channel;
                    return {
                        status: res.status,
                        dom_text: document.getElementById("post-box").textContent,
                        token_preserved: window.__pageToken === "stay-alive-token-26"
                    };
                }""")
                exp3 = {
                    "status": 200,
                    "dom_text": "sync:ajax",
                    "token_preserved": True,
                }
                cases.append({"name": "ajax_post_exchange_no_reload", "passed": c3 == exp3, "expected": exp3, "actual": c3})

                c4 = page.evaluate("""() => ({
                    has_xhr: typeof XMLHttpRequest === "function",
                    has_fetch: typeof fetch === "function",
                    has_legacy_activex: typeof ActiveXObject !== "undefined",
                    external_cdn_scripts: document.querySelectorAll("script[src]").length
                })""")
                c4["get_demo_requests"] = sum(1 for m, pth in state["requests"] if m == "GET" and pth == "/demo_test.txt")
                exp4 = {
                    "has_xhr": True,
                    "has_fetch": True,
                    "has_legacy_activex": False,
                    "external_cdn_scripts": 0,
                    "get_demo_requests": 2,
                }
                cases.append({"name": "ajax_abstraction_vs_native_xhr", "passed": c4 == exp4, "expected": exp4, "actual": c4})
            finally:
                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/jquery-ajax-intro-lab/explore-ajax-intro.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-ajax-intro.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:jQuery

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a876.zip

下载课程关联工程包:jQuery

课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a879.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习