AJAX 简介
Fetching data without a page reload: request, response, and PHP's role.
What AJAX is
AJAX is not a technology but a pattern: no navigation, JS requests in the background, and the DOM updates in place.
The XML in the name is obsolete — JSON dominates. PHP's only job is to emit data instead of an HTML page.
A full round trip
- A user event fires (click, typing, scroll)
- JS sends a
fetchto a PHP script - PHP handles it and emits JSON
- JS parses the JSON and updates the DOM
// 前端:请求 /api/time.php
async function loadTime() {
const res = await fetch("/api/time.php");
if (!res.ok) throw new Error("HTTP " + res.status);
const data = await res.json(); // 解析 JSON
document.querySelector("#out").textContent = data.now;
}
loadTime();<?php
// /api/time.php
header("Content-Type: application/json; charset=utf-8");
echo json_encode([
"ok" => true,
"now" => "2023-11-15 06:13:20",
], JSON_UNESCAPED_UNICODE);{"ok":true,"now":"2023-11-15 06:13:20"}The only PHP addition is the Content-Type header. **Without it res.json() may refuse to parse** — some browsers check MIME strictly.
Classic request vs AJAX
| Aspect | Classic | AJAX |
|---|---|---|
| Page reload | 整页重载 | 不刷新 |
| Response | 完整 HTML | JSON / XML / 片段 |
| State | 丢失(滚动位置、表单) | 保留 |
| Server side | 一样 | 一样 |
| SEO | 友好 | 需要额外处理 |
fetch vs XMLHttpRequest
fetch is the modern standard, Promise-based and terse. XMLHttpRequest is the veteran still found in older code.
// fetch(推荐)
const res = await fetch("/api/users");
const users = await res.json();
// XMLHttpRequest(老写法)
const xhr = new XMLHttpRequest();
xhr.open("GET", "/api/users");
xhr.onload = () => {
if (xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
}
};
xhr.send();fetch does not reject on 4xx/5xx, only on network failure. Always check res.ok yourself.Common uses
- Async form submit —— no navigation, inline errors
- Live search —— query as you type
- Infinite scroll —— append content
- Polling / long-poll —— messages, progress, poll results
- Partial refresh —— likes, bookmarks, cart counts
AJAX 是什么
AJAX(Asynchronous JavaScript and XML)不是技术,是一种用法:页面不跳转,JS 在后台发请求,拿到数据后局部更新 DOM。
名字里的 XML 早就过时了,现在几乎都用 JSON。PHP 端要做的只有一件事:输出数据而不是 HTML 页面。
一次完整往返
- 用户触发事件(点击、输入、滚动)
- JS 发
fetch请求到某个 PHP 脚本 - PHP 处理,输出 JSON
- JS 解析 JSON,更新 DOM
// 前端:请求 /api/time.php
async function loadTime() {
const res = await fetch("/api/time.php");
if (!res.ok) throw new Error("HTTP " + res.status);
const data = await res.json(); // 解析 JSON
document.querySelector("#out").textContent = data.now;
}
loadTime();<?php
// /api/time.php
header("Content-Type: application/json; charset=utf-8");
echo json_encode([
"ok" => true,
"now" => "2023-11-15 06:13:20",
], JSON_UNESCAPED_UNICODE);{"ok":true,"now":"2023-11-15 06:13:20"}PHP 端只多了一行 header("Content-Type: application/json")。**没有这行,res.json() 可能拒绝解析**(部分浏览器严格检查 MIME)。
传统请求 vs AJAX
| 对比项 | 传统请求 | AJAX |
|---|---|---|
| 页面刷新 | 整页重载 | 不刷新 |
| 响应内容 | 完整 HTML | JSON / XML / 片段 |
| 页面状态 | 丢失(滚动位置、表单) | 保留 |
| 服务端 | 一样 | 一样 |
| SEO | 友好 | 需要额外处理 |
prerender / 静态化。fetch 与 XMLHttpRequest
fetch 是现代标准,基于 Promise,代码短。XMLHttpRequest 是老兵,老项目里仍然常见。
// fetch(推荐)
const res = await fetch("/api/users");
const users = await res.json();
// XMLHttpRequest(老写法)
const xhr = new XMLHttpRequest();
xhr.open("GET", "/api/users");
xhr.onload = () => {
if (xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
}
};
xhr.send();fetch 不会因为 4xx/5xx 而 reject,只有网络故障才 reject。所以必须自己检查 res.ok——这是最常见的疏漏。AJAX 的常见用途
- 表单异步提交 —— 不跳转,就地显示错误
- 实时搜索 —— 边输边查
- 无限滚动 / 分页 —— 追加内容
- 轮询 / 长连接 —— 消息、进度、投票结果
- 局部刷新 —— 点赞、收藏、购物车数量