AJAX – onreadystatechange 事件
onreadystatechange
事件是 XMLHttpRequest
对象的一个关键事件,用于处理 AJAX 请求的不同状态。在请求过程中,浏览器会根据请求的状态更新 readyState
,而 onreadystatechange
事件的触发则是根据 readyState
变化来决定的。
1. readyState
状态详解
readyState
属性表示请求的当前状态。readyState
有 5 个值,从 0 到 4,分别代表不同的状态:
readyState 值 | 状态名称 | 描述 |
---|---|---|
0 | UNSENT | XMLHttpRequest 对象已创建,但尚未调用 open() 方法。 |
1 | OPENED | 调用了 open() 方法,且请求尚未发送。 |
2 | HEADERS_RECEIVED | 请求已发送,并且服务器响应头已收到。 |
3 | LOADING | 正在接收响应体(响应部分数据已收到)。 |
4 | DONE | 请求完成,响应体已完全接收。 |
2. onreadystatechange
事件的工作原理
onreadystatechange
事件会在 readyState
发生变化时被触发。通常,在事件处理函数中,需要检查 readyState
是否为 4(表示请求已完成),以及 status
是否为 200(表示请求成功)。
3. 示例:使用 onreadystatechange
处理请求
var xhr = new XMLHttpRequest(); // 创建 XMLHttpRequest 对象
xhr.open("GET", "data.txt", true); // 配置请求方法和 URL
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) { // 当请求完成(readyState 为 4)
if (xhr.status === 200) { // 如果请求成功(status 为 200)
console.log("服务器返回的数据:", xhr.responseText);
} else {
console.error("请求失败,状态码:", xhr.status); // 处理请求失败的情况
}
}
};
xhr.send(); // 发送请求
4. 代码解析
- 创建请求:
xhr = new XMLHttpRequest();
创建一个新的XMLHttpRequest
对象。 - 配置请求:
xhr.open("GET", "data.txt", true);
配置请求的方法、URL 及是否异步(true
为异步)。 - 监听
onreadystatechange
: 通过设置xhr.onreadystatechange
来监听请求的状态变化。当readyState
变化时,回调函数会执行。- 检查
readyState
: 当readyState === 4
时,表示请求已经完成。 - 检查
status
: 如果status === 200
,表示请求成功,返回数据可用。如果不是 200,表示请求失败。
- 检查
- 发送请求:
xhr.send();
发送请求。
5. 完整的 onreadystatechange
事件处理流程
在 AJAX 请求中,onreadystatechange
的事件会多次触发,通常的处理逻辑如下:
var xhr = new XMLHttpRequest();
xhr.open("GET", "data.txt", true);
xhr.onreadystatechange = function() {
// 当 readyState 为 4(完成)时,检查响应状态
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// 请求成功,处理返回的内容
console.log("请求成功:", xhr.responseText);
} else {
// 请求失败,处理错误
console.error("请求失败,状态码:", xhr.status);
}
} else if (xhr.readyState === 3) {
// 在加载过程中处理请求
console.log("数据正在加载...");
} else if (xhr.readyState === 2) {
// 请求头已接收
console.log("响应头已接收...");
}
};
// 发送请求
xhr.send();
6. 状态码与状态名称的常见示例
- 200 OK:请求成功。
- 404 Not Found:服务器没有找到请求的资源。
- 500 Internal Server Error:服务器内部错误,无法处理请求。
7. readyState
变化示例
var xhr = new XMLHttpRequest();
xhr.open("GET", "data.txt", true);
xhr.onreadystatechange = function() {
console.log("readyState变化:", xhr.readyState); // 打印每次 readyState 变化时的值
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log("请求成功,返回数据:", xhr.responseText);
} else {
console.error("请求失败,状态码:", xhr.status);
}
}
};
xhr.send();
输出:
readyState变化: 1
readyState变化: 2
readyState变化: 3
readyState变化: 4
8. 小结
onreadystatechange
:事件在readyState
变化时触发,用于监听请求的状态。readyState
:表示请求的状态,有五个值:0 到 4。- 当
readyState
为 4 且status
为 200 时,表示请求成功,可以处理返回的数据。 - 通过
xhr.status
获取 HTTP 响应状态码。
9. 推荐:使用 fetch()
代替 onreadystatechange
虽然 XMLHttpRequest
和 onreadystatechange
事件是传统的 AJAX 方法,但现代浏览器更推荐使用 fetch()
,其 API 更简洁、基于 Promises,适用于大多数场景。fetch()
支持链式调用,可以有效地减少回调函数的复杂性。
发表回复