jQuery AJAX 简介
核对 AJAX 局部无刷新数据交换原理、HTTP GET/POST 多格式响应读取,以及 jQuery 封装跨浏览器异步请求的工程价值。
学完这一章,你能够
- 核对 AJAX 局部无刷新数据交换原理、HTTP GET/POST 多格式响应读取,以及 jQuery 封装跨浏览器异步请求的工程价值。
什么是 AJAX 与无刷新局部更新
AJAX 全称为 Asynchronous JavaScript and XML(异步 JavaScript 与 XML),是一类在后台与服务器交换数据、并在不重载整个页面的前提下动态更新网页局部区域的技术方案。尽管名称中包含 XML,实际传输载荷广泛涵盖纯文本、HTML 片段与 JSON。
地图缩放加载瓦片、视频评论与动态信息流、即时表单校验等交互密集型 Web 应用均依赖 AJAX 实现流畅体验(例如早期地图、社交动态与视频站点的局部刷新场景)。后续章节及对应的 AJAX 专题将进一步系统展开具体接口与参数细节。
jQuery AJAX 实例:点击按钮局部载入外部内容
典型入门场景是在页面放置目标容器 `#div1`(初始标题为“使用 jQuery AJAX 修改文本内容”)和按钮“获取外部内容”,点击按钮后通过 `$('#div1').load(...)` 异步拉取外部文本并替换容器内容。本站在本地 `127.0.0.1` 回环服务器与离线 Chromium 中实测:点击 `#btn1` 请求 `/demo_test.txt` 后,`#div1` 内的 `<h2>` 更新为“外部文本已载入”并插入 `<p id="p1">局部更新成功,页面未重载。</p>`,同时页面全局状态令牌 `window.__pageToken` 保持原值 `stay-alive-token-26`,直接证明未触发整页刷新。
jQuery AJAX 方法与跨浏览器封装意义
jQuery 提供了一组简洁的 AJAX 快捷与底层方法,可通过 HTTP GET 和 HTTP POST 从服务器获取纯文本、HTML、XML 或 JSON 数据,并按需直接写入被选 DOM 元素。本站回环实测同源 GET 请求 `/demo_test.txt`、`/api/sample.html`、`/api/sample.json`(解析得 `mode='json', items=3`)与 `/api/sample.xml`(解析得 `<msg>XML_OK</msg>`)全部返回 HTTP 200;同时实测 `$.post('/api/echo', {action: 'sync', channel: 'ajax'})` 在不刷新页面的前提下将回显结果 `sync:ajax` 写入 `#post-box`。
早期不同浏览器对原生异步对象的实现存在明显差异(例如旧版 IE 的 `ActiveXObject` 与标准 `XMLHttpRequest`),手写原生 AJAX 往往需要大量兼容性分支检测。jQuery 将底层差异统一封装为单行调用;现代浏览器(含本次实测的 Chromium:`has_xhr=true`、`has_fetch=true`、`has_legacy_activex=false`)虽已统一支持 `XMLHttpRequest` 与 `fetch`,但理解 jQuery AJAX 封装仍有助于维护存量项目与理解异步请求生命周期。
原生 AJAX 兼容性痛点与 jQuery 封装说明
| 关注点 | 技术背景与封装作用 |
| 跨浏览器异步编程简化 | 手写常规 AJAX 在历史浏览器中需针对不同实现编写分支兼容代码;jQuery 将请求发送、状态检查与结果注入封装为统一接口,仅需少量代码即可完成异步数据交换。 |
通过本地 127.0.0.1 回环服务与离线 Chromium 实测 AJAX 无刷新局部更新及多格式数据交换
展开查看收起
"""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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
核心价值是在后台异步与服务器交换数据并局部更新 DOM,避免整页重载带来的白屏与状态丢失;可在页面初始化时设置内存变量(如 window.__pageToken)并观察请求完成后该变量是否保持不变,同时核对网络面板仅发出异步请求。