AJAX – 创建 XMLHttpRequest 对象

XMLHttpRequest(XHR)对象是 JavaScript 提供的 核心 AJAX 组件,用于在网页与服务器之间进行数据交换,无需刷新页面即可更新内容。


1. 创建 XMLHttpRequest 对象

在 JavaScript 中,可以使用以下方式创建 XMLHttpRequest 对象:

var xhr = new XMLHttpRequest();

说明:

  • XMLHttpRequest 是浏览器内置的 API,无需额外引入库。
  • xhr 变量存储 XMLHttpRequest 对象,可以用于发送 HTTP 请求。

2. 使用 XMLHttpRequest 发送请求

一个完整的 AJAX 请求流程如下:

// 1. 创建 XMLHttpRequest 对象
var xhr = new XMLHttpRequest();

// 2. 配置请求:指定方法、URL 和是否异步
xhr.open("GET", "data.txt", true);

// 3. 监听请求状态变化
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log("服务器返回的数据:", xhr.responseText);
    }
};

// 4. 发送请求
xhr.send();

代码解析:

  • xhr.open(method, url, async):初始化请求
    • method:请求方式,如 "GET""POST"
    • url:服务器接口地址,如 "data.txt"
    • async:是否异步(true 为异步,false 为同步)。
  • xhr.onreadystatechange:监听请求状态变化,readyState === 4status === 200 表示请求成功。
  • xhr.send():发送请求(GET 请求时不需要参数)。

3. XMLHttpRequest 的 readyState 说明

readyState 代表请求的状态变化:

readyState 值状态说明
0UNSENT未初始化,还未调用 open()
1OPENED已初始化,调用了 open() 但未发送请求
2HEADERS_RECEIVED已发送请求,收到响应头
3LOADING正在接收数据(部分数据已到达)
4DONE请求完成,可获取响应

示例:打印 readyState 变化

xhr.onreadystatechange = function() {
    console.log("readyState:", xhr.readyState);
};


4. 处理服务器响应

服务器响应的数据可通过 xhr.responseText 访问:

xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            console.log("成功:", xhr.responseText);
        } else {
            console.error("请求失败,状态码:", xhr.status);
        }
    }
};

常见的 HTTP 状态码

状态码说明
200请求成功
404资源未找到
500服务器内部错误

5. 发送不同类型的请求

GET 请求

xhr.open("GET", "data.json", true);
xhr.send();

POST 请求

xhr.open("POST", "submit.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("name=张三&age=25");

注意

  • setRequestHeader() 用于设置请求头,例如 Content-Type
  • send(data) 发送数据(POST 请求时需要)。

6. 使用 JSON 数据

服务器返回 JSON

如果服务器返回的是 JSON:

{ "name": "张三", "age": 25 }

JavaScript 解析 JSON

xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var data = JSON.parse(xhr.responseText);
        console.log("姓名:", data.name);
        console.log("年龄:", data.age);
    }
};

解析 JSON 的关键:

JSON.parse(xhr.responseText);


7. 处理 AJAX 请求错误

为了提高用户体验,需要处理错误:

xhr.onerror = function() {
    console.error("请求出错!");
};
xhr.ontimeout = function() {
    console.error("请求超时!");
};
xhr.timeout = 5000; // 设置超时时间(毫秒)


总结

  • XMLHttpRequest 是实现 AJAX 的基础。
  • 通过 open() 配置请求,send() 发送请求,onreadystatechange 监听状态变化。
  • readyState === 4 && status === 200 表示请求成功。
  • responseText 读取服务器返回的内容。
  • 解析 JSON 时需使用 JSON.parse()
  • 处理错误和超时,避免用户等待太久。

🚀 推荐使用 fetch() 代替 XMLHttpRequest,语法更简洁!