15. xhr 对象如何发起一个请求
总结
XMLHttpRequest
(简称 XHR)是浏览器提供的用于发送 HTTP 请求的 JavaScript 对象。- 常用于实现 AJAX 请求,实现页面局部刷新或与后端进行数据交互。
- 基本流程包括:创建对象、配置请求、设置回调、发送请求。
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.baidu.com");
xhr.onreadystatechange = function () {if (xhr.readyState === 4 && xhr.status === 200) {}
};
xhr.send();
使用步骤详解
1. 创建 XMLHttpRequest
实例
var xhr = new XMLHttpRequest();
2. 配置请求方式和 URL
使用 open()
方法配置请求类型、URL 和是否异步。
xhr.open("GET", "http://www.baidu.com", true);
参数说明:
'GET'
:请求方法,也可以是POST
、PUT
等。'http://www.baidu.com'
:请求的目标 URL。true
:是否异步,默认为true
。
3. 设置状态变化回调函数
通过 onreadystatechange
监听请求状态变化:
xhr.onreadystatechange = function () {if (xhr.readyState === 4 && xhr.status === 200) {console.log(xhr.responseText); // 请求成功返回的数据}
};
readyState === 4
表示请求已完成。status === 200
表示响应状态码为成功。
4. 发送请求
xhr.send();
如果是 POST
请求,可以在 send()
中传入请求体:
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("name=value&name2=value2");
完整示例(GET 请求)
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
xhr.onreadystatechange = function () {if (xhr.readyState === 4 && xhr.status === 200) {console.log("响应数据:", xhr.responseText);}
};
xhr.send();
完整示例(POST 请求)
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://api.example.com/submit", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {if (xhr.readyState === 4 && xhr.status === 200) {console.log("提交结果:", xhr.responseText);}
};
xhr.send("username=test&password=123456");
注意事项
- 需处理跨域问题(CORS),服务器需设置合适的响应头。
- 需处理错误状态,如 [status](file://d:\Code\Gitee\video-project\node\routes\dept\controller.js#L171-L190) 不为 2xx 的情况。
- 推荐使用
fetch
或第三方库(如 Axios)替代XMLHttpRequest
,代码更简洁易维护。
readyState 状态码说明
readyState | 状态描述 |
---|---|
0 | 未初始化,尚未调用 open() 方法 |
1 | 已打开,已调用 open() 方法,尚未调用 send() |
2 | 已发送,已接收到响应头 |
3 | 接收中,正在下载响应体 |
4 | 完成,响应内容已完成下载 |
HTTP 状态码简要
状态码 | 含义 |
---|---|
200 | 请求成功 |
404 | 资源未找到 |
500 | 服务器内部错误 |
403 | 禁止访问 |
401 | 未授权 |