XMLHttpRequest 五个步骤
使用 XMLHttpRequest 发送 Ajax 请求的完整流程
问题
使用原生 XMLHttpRequest 发送 Ajax 请求需要哪五个步骤?
解答
五个步骤
- 创建 XMLHttpRequest 对象
- 调用 open() 方法
- 设置请求头(可选)
- 注册状态变化回调
- 调用 send() 方法
完整示例
// 1. 创建 XMLHttpRequest 对象
const xhr = new XMLHttpRequest();
// 2. 调用 open() 方法,设置请求方式和 URL
// 参数:method, url, async(默认 true)
xhr.open('GET', 'https://api.example.com/data', true);
// 3. 设置请求头(GET 请求可省略,POST 请求通常需要)
xhr.setRequestHeader('Content-Type', 'application/json');
// 4. 注册 onreadystatechange 回调函数
xhr.onreadystatechange = function () {
// readyState 为 4 表示请求完成
if (xhr.readyState === 4) {
// status 为 200 表示成功
if (xhr.status === 200) {
console.log('响应数据:', xhr.responseText);
} else {
console.error('请求失败:', xhr.status);
}
}
};
// 5. 调用 send() 方法发送请求
// GET 请求传 null,POST 请求传请求体
xhr.send(null);
POST 请求示例
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.example.com/users', true);
// POST 请求需要设置 Content-Type
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
console.log('创建成功:', response);
}
};
// 发送 JSON 数据
xhr.send(JSON.stringify({ name: '张三', age: 25 }));
readyState 的五个状态
| 值 | 状态 | 说明 |
|---|---|---|
| 0 | UNSENT | 对象已创建,未调用 open() |
| 1 | OPENED | 已调用 open() |
| 2 | HEADERS_RECEIVED | 已调用 send(),收到响应头 |
| 3 | LOADING | 正在接收响应体 |
| 4 | DONE | 请求完成 |
封装成 Promise
function ajax(options) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
const { method = 'GET', url, data = null, headers = {} } = options;
xhr.open(method, url, true);
// 设置请求头
Object.keys(headers).forEach(key => {
xhr.setRequestHeader(key, headers[key]);
});
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(JSON.parse(xhr.responseText));
} else {
reject(new Error(`请求失败: ${xhr.status}`));
}
}
};
xhr.onerror = function () {
reject(new Error('网络错误'));
};
xhr.send(data ? JSON.stringify(data) : null);
});
}
// 使用
ajax({
method: 'GET',
url: 'https://api.example.com/data'
}).then(data => {
console.log(data);
});
关键点
- 五个步骤:创建对象 → open() → setRequestHeader() → onreadystatechange → send()
- readyState === 4 表示请求完成,需配合 status 判断是否成功
- GET 请求参数拼接在 URL 上,send(null);POST 请求数据放在 send() 中
- open() 第三个参数控制同步/异步,默认 true(异步)
- 现代开发中更推荐使用 fetch API,但面试常考 XHR 原理
目录