AJAX 简介

Fetching data without a page reload: request, response, and PHP's role.

Beginner
Key PointsAJAX is just an HTTP request from JS — the PHP side is identical to a normal page request.

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

  1. A user event fires (click, typing, scroll)
  2. JS sends a fetch to a PHP script
  3. PHP handles it and emits JSON
  4. JS parses the JSON and updates the DOM
JavaScript
// 前端:请求 /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
<?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);
Output
{"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

AspectClassicAJAX
Page reload整页重载不刷新
Response完整 HTMLJSON / XML / 片段
State丢失(滚动位置、表单)保留
Server side一样一样
SEO友好需要额外处理
AJAX pages are not SEO friendly since content is absent from the initial HTML. Use SSR or prerendering where SEO matters.

fetch vs XMLHttpRequest

fetch is the modern standard, Promise-based and terse. XMLHttpRequest is the veteran still found in older code.

JavaScript
// 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

Friends & Partners