XMLHttpRequest.status 属性深度解析
词源分解与功能定位
status 属性名称源自HTTP协议状态码体系:
status(状态):表示HTTP请求/响应的处理结果
数值型标识:采用3位数字编码规范(RFC 2616标准)
该属性是XHR对象的核心响应标识,用于精确判断服务器对请求的处理结果
语法结构
基础访问方式:
const httpStatus = xhr.status;
属性特征:
只读属性(unsigned short类型)
标准HTTP状态码(100-599)
请求未完成时值为0
状态码分类详解
1xx 信息类
2xx 成功类
3xx 重定向类
4xx 客户端错误
5xx 服务端错误
属性示例与输出
基础检测示例
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/data', true);
xhr.onload = function() {
console.log(`状态码: ${xhr.status}`);
if(xhr.status === 200) {
console.log('响应数据:', xhr.responseText);
}
};
xhr.send();典型输出:
状态码: 200
响应数据: {...}应用场景分析
1. 错误分级处理
xhr.onreadystatechange = function() {
if(xhr.readyState === 4) {
switch(Math.floor(xhr.status/100)) {
case 2: successHandler(xhr.response); break;
case 4: clientErrorHandler(xhr.status); break;
case 5: serverErrorHandler(); break;
}
}
};2. 缓存验证
if(xhr.status === 304) {
loadFromCache();
} else {
updateCache(xhr.response);
}3. 认证流程
if(xhr.status === 401) {
showLoginModal();
storePendingRequest(xhr);
}注意事项
时序问题:
必须在readyState=4时检查status
早期状态读取会得到0值
跨域限制:
跨域请求仅能获取基本状态码(200/404等)
详细状态信息受同源策略限制
特殊状态:
graph LR A[0:未发送] --> B[2xx:成功] A --> C[3xx:重定向] A --> D[4xx:客户端错误] A --> E[5xx:服务端错误] style A fill:#f9f,stroke:#333 style B fill:#9f9,stroke:#090
综合比较表
现代替代方案
Fetch API状态处理
fetch('/api')
.then(res => {
console.log(res.status); // 等效status属性
if(!res.ok) throw new Error(res.statusText);
return res.json();
});性能优化建议
状态检测优化:
// 推荐:结合readyState检测
if(xhr.readyState === 4 && xhr.status === 200) {
// 处理逻辑
}错误防御:
try {
if(xhr.status >= 400) {
handleError(xhr.statusText);
}
} catch(e) {
console.error('状态处理异常:', e);
}缓存策略:
if(xhr.status === 304) {
useCachedVersion();
} else if(xhr.status === 200) {
refreshCache(xhr.response);
}通过深入理解status机制,开发者可以构建更健壮的HTTP通信系统,实现精确的错误处理和用户体验优化