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

在本地 127.0.0.1 回环服务与离线 Chromium 中实测 .load() 全文加载、#p1 片段提取、404 回调与 POST 负载切换

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-ajax-load.py
explore-ajax-load.py224 行
"""Offline Playwright Chromium lab for jQuery Chapter 27 (ajax-load)."""
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 load() Lab</title></head>
<body>
  <div id="div1">初始内容1</div>
  <div id="div2">初始内容2</div>
  <div id="div3">初始内容3</div>
  <div id="div4">初始内容4</div>
  <button id="btn-ok" type="button">加载有效文件</button>
  <button id="btn-err" type="button">加载缺失文件</button>
  <script>
    window.__alerts = [];
    window.alert = function (msg) { window.__alerts.push(String(msg)); };
    (function (global) {
      function wrap(nodes) {
        const list = Array.from(nodes);
        return {
          click(fn) {
            for (const el of list) el.addEventListener("click", fn);
            return this;
          },
          load(urlSpec, dataOrCb, maybeCb) {
            let data = null;
            let cb = null;
            if (typeof dataOrCb === "function") {
              cb = dataOrCb;
            } else {
              data = dataOrCb;
              cb = maybeCb;
            }
            const spaceIdx = urlSpec.indexOf(" ");
            const url = spaceIdx >= 0 ? urlSpec.slice(0, spaceIdx) : urlSpec;
            const selector = spaceIdx >= 0 ? urlSpec.slice(spaceIdx + 1).trim() : null;

            const xhr = new XMLHttpRequest();
            const isPost = data !== null && typeof data === "object";
            const method = isPost ? "POST" : "GET";
            const reqUrl = !isPost && typeof data === "string" && data ? (url + "?" + data) : url;
            xhr.open(method, reqUrl, true);
            if (isPost) {
              xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            }
            xhr.onload = function () {
              const ok = xhr.status >= 200 && xhr.status < 300;
              const statusTxt = ok ? "success" : "error";
              if (ok) {
                let content = xhr.responseText;
                if (selector) {
                  const doc = new DOMParser().parseFromString(content, "text/html");
                  const matched = Array.from(doc.querySelectorAll(selector));
                  content = matched.map(el => el.outerHTML).join("");
                }
                for (const el of list) el.innerHTML = content;
              }
              if (cb) cb(xhr.responseText, statusTxt, xhr);
            };
            xhr.send(isPost ? new URLSearchParams(data).toString() : null);
            return this;
          }
        };
      }
      global.$ = function (arg) {
        if (typeof arg === "string") return wrap(document.querySelectorAll(arg));
        return wrap([]);
      };
    })(window);

    $("#btn-ok").click(function () {
      $("#div4").load("/demo_test.txt", function (responseTxt, statusTxt, xhr) {
        if (statusTxt === "success") alert("外部内容加载成功!");
        if (statusTxt === "error") alert("Error: " + xhr.status + ": " + xhr.statusText);
        window.__okDone = { statusTxt, httpStatus: xhr.status, responseLen: responseTxt.length };
      });
    });

    $("#btn-err").click(function () {
      $("#div4").load("/missing_file.txt", function (responseTxt, statusTxt, xhr) {
        if (statusTxt === "success") alert("外部内容加载成功!");
        if (statusTxt === "error") alert("Error: " + xhr.status + ": " + xhr.statusText);
        window.__errDone = { statusTxt, httpStatus: xhr.status, statusText: xhr.statusText };
      });
    });
  </script>
</body>
</html>
"""

DEMO_TEXT = '<h2>jQuery AJAX 是个非常棒的功能!</h2>\n<p id="p1">这是段落的一些文本。</p>'


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

        def _send(self, code, content_type, body, message=None):
            data = body.encode("utf-8")
            self.send_response(code, message)
            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["log"].append({"method": "GET", "path": 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", DEMO_TEXT)
            else:
                self._send(404, "text/plain; charset=utf-8", "File Not Found", "Not Found")

        def do_POST(self):
            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()}
            state["log"].append({"method": "POST", "path": self.path, "params": params})
            if self.path == "/echo_load":
                html = f'<p class="echo">topic={params.get("topic","")},step={params.get("step","")}</p>'
                self._send(200, "text/html; charset=utf-8", html)
            else:
                self._send(404, "text/plain; charset=utf-8", "Not Found", "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 = {"log": []}
    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 + "/")

                page.evaluate('() => { $("#div1").load("/demo_test.txt", () => { window.__c1Done = true; }); }')
                page.wait_for_function("() => window.__c1Done === true")
                c1 = page.evaluate("""() => ({
                    h2_text: document.querySelector("#div1 h2").textContent,
                    p1_text: document.querySelector("#div1 #p1").textContent,
                    child_count: document.querySelector("#div1").children.length
                })""")
                exp1 = {
                    "h2_text": "jQuery AJAX 是个非常棒的功能!",
                    "p1_text": "这是段落的一些文本。",
                    "child_count": 2,
                }
                cases.append({"name": "load_full_document_into_div", "passed": c1 == exp1, "expected": exp1, "actual": c1})

                page.evaluate('() => { $("#div2").load("/demo_test.txt #p1", () => { window.__c2Done = true; }); }')
                page.wait_for_function("() => window.__c2Done === true")
                c2 = page.evaluate("""() => ({
                    has_h2: document.querySelector("#div2 h2") !== null,
                    p1_text: document.querySelector("#div2 #p1").textContent,
                    child_count: document.querySelector("#div2").children.length
                })""")
                exp2 = {
                    "has_h2": False,
                    "p1_text": "这是段落的一些文本。",
                    "child_count": 1,
                }
                cases.append({"name": "load_selector_fragment_p1", "passed": c2 == exp2, "expected": exp2, "actual": c2})

                page.click("#btn-ok")
                page.wait_for_function("() => Boolean(window.__okDone)")
                page.click("#btn-err")
                page.wait_for_function("() => Boolean(window.__errDone)")
                c3 = page.evaluate("""() => ({
                    ok: window.__okDone,
                    err: window.__errDone,
                    alerts: window.__alerts
                })""")
                exp3 = {
                    "ok": {"statusTxt": "success", "httpStatus": 200, "responseLen": len(DEMO_TEXT)},
                    "err": {"statusTxt": "error", "httpStatus": 404, "statusText": "Not Found"},
                    "alerts": ["外部内容加载成功!", "Error: 404: Not Found"],
                }
                cases.append({"name": "load_callback_success_and_404_error", "passed": c3 == exp3, "expected": exp3, "actual": c3})

                page.evaluate('() => { $("#div3").load("/echo_load", { topic: "ajax", step: "2" }, () => { window.__c4Done = true; }); }')
                page.wait_for_function("() => window.__c4Done === true")
                post_entry = next(item for item in state["log"] if item["path"] == "/echo_load")
                c4 = {
                    "http_method": post_entry["method"],
                    "received_params": post_entry["params"],
                    "div3_echo": page.locator("#div3 .echo").text_content(),
                }
                exp4 = {
                    "http_method": "POST",
                    "received_params": {"topic": "ajax", "step": "2"},
                    "div3_echo": "topic=ajax,step=2",
                }
                cases.append({"name": "load_with_data_payload_switches_to_post", "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-load-lab/explore-ajax-load.py

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

下载课程关联工程包:jQuery

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

下载课程关联工程包:jQuery

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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