jQuery load() 方法
核对 $(selector).load(URL, data, callback) 的完整语法、URL 附加选择器局部抓取、POST 参数切换以及回调函数三参数实测行为。
学完这一章,你能够
- 核对 $(selector).load(URL, data, callback) 的完整语法、URL 附加选择器局部抓取、POST 参数切换以及回调函数三参数实测行为。
load() 方法的作用与完整语法
`load()` 是 jQuery 中最简洁实用的 AJAX 方法之一,用于向服务器请求数据并将返回结果直接写入被选元素的内部 HTML。其完整语法为 `$(selector).load(URL, data, callback)`:必需参数 `URL` 指定目标资源地址;可选参数 `data` 指定随请求发送的查询字符串或键值对象(传入普通对象时 jQuery 会自动改用 HTTP POST 发送);可选参数 `callback` 指定加载完成后执行的回调函数。
整页加载与 URL 附加选择器片段加载
假设服务端示例文本 `demo_test.txt` 包含两段 HTML:`<h2>jQuery AJAX 是个非常棒的功能!</h2>` 与 `<p id="p1">这是段落的一些文本。</p>`。调用 `$('#div1').load('demo_test.txt')` 会把文件全部内容注入 `#div1`。本站 127.0.0.1 回环服务与离线 Chromium 实测:`#div1` 写入后共有 2 个子元素,`h2` 与 `#p1` 文本均完整呈现。
`URL` 参数尾部还支持以空格分隔附加一个 jQuery/CSS 选择器,例如 `$('#div2').load('demo_test.txt #p1')`,只截取响应文档中匹配 `#p1` 的片段注入目标容器。本站实测 `#div2` 中仅写入 1 个子节点 `#p1`(文本为“这是段落的一些文本。”),且 `<h2>` 未被插入(`has_h2=false`)。此外,本站补充验证传入键值对象 `$('#div3').load('/echo_load', {topic: 'ajax', step: '2'})` 时,请求自动切换为 HTTP `POST` 并将服务端回显 `topic=ajax,step=2` 注入 `#div3`。
load() 完成回调的三个参数与成功/失败处理
可选回调函数签名为 `function(responseTxt, statusTxt, xhr)`,其中 `responseTxt` 保存服务端返回的原始文本,`statusTxt` 标识请求状态(常见为 `"success"` 或 `"error"`),`xhr` 为底层的 `XMLHttpRequest` 对象(可读取 `xhr.status` 与 `xhr.statusText`)。本站离线 Chromium 实测点击成功按钮加载 `/demo_test.txt` 时,回调收到 `statusTxt='success'`、`xhr.status=200`、`responseTxt.length=56` 并触发提示“外部内容加载成功!”;点击失败按钮请求不存在的 `/missing_file.txt` 时,回调收到 `statusTxt='error'`、`xhr.status=404`、`xhr.statusText='Not Found'` 并输出 `Error: 404: Not Found`。
在本地 127.0.0.1 回环服务与离线 Chromium 中实测 .load() 全文加载、#p1 片段提取、404 回调与 POST 负载切换
"""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()
- 核对整文件加载得 2 个子节点、附带 #p1 选择器仅载入 1 个段落、200/404 回调三参数与提示消息完全一致,以及传入对象 data 自动转为 POST。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:7ee773c17a33f4fa928d591dcfa8b94be038ede49b027bb7589066bfe13bf0db
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:6a060c1daa010c661d30a5c34a8e5c72c9a0714e52d72e687cd80d0f3e07e2bf
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 $('#box').load('/demo_test.txt #p1', cb) 中,浏览器向服务器请求的是完整文件还是仅请求 #p1?回调函数中的三个参数分别代表什么?
展开参考解答
浏览器仍向服务器请求完整的 /demo_test.txt 响应,随后在客户端解析 HTML 并仅截取匹配 #p1 的节点写入 #box;回调三参数依次为 responseTxt(响应原文)、statusTxt('success' 或 'error' 等状态)与 xhr(XMLHttpRequest 实例)。