HTTP 异步请求
fetch
来自ES6,是一个 API,无需安装
1fetch("https://www.krjojo.com/")
2 .then(response => {
3 if (!response.ok) {
4 throw new Error("请求失败,状态码:" + response.status);
5 }
6 return response.json();
7 })
8 .then(data => {
9 // 请求成功,处理响应数据
10 console.log("成功获取数据:", data);
11 })
12 .catch(error => {
13 // 请求失败,处理错误
14 console.error(error);
15 });
流式读取内容
xhr
XMLHttpRequest
来自IE5,后成为W3C标准接口
GET 请求示例
1// 创建一个新的XHR对象
2const xhr = new XMLHttpRequest();
3
4// 配置请求
5xhr.open("GET", "https://www.krjojo.com/", true);
6
7// 配置头
8xhr.setRequestHeader("Content-Type", "application/json");
9
10// 设置响应处理函数
11xhr.onload = function() {
12 if (xhr.status === 200) {
13 // 请求成功
14 const responseData = xhr.responseText;
15 console.log("成功获取数据:", responseData);
16 } else {
17 // 请求失败
18 console.error("请求失败,状态码:" + xhr.status);
19 }
20};
21
22// 发起请求
23xhr.send();
POST 请求示例
1const xhr = new XMLHttpRequest();
2
3xhr.open("POST", "/submit", true);
4
5xhr.setRequestHeader("Content-Type", "application/json");
6
7xhr.onload = () => {
8 if (xhr.status === 200) {
9 console.log("成功:", xhr.responseText);
10 }
11};
12
13xhr.send(JSON.stringify({ username: "alice" }));
Axios
用xhr进行了二次封装的第三方请求库,支持异步,非浏览器自带
1const axios = require("axios");
2
3axios.get("https://www.krjojo.com/", {
4 params: {
5 post: 12345
6 }
7 })
8 .then(function (response) {
9 // 处理成功情况
10 console.log(response);
11 })
12 .catch(function (error) {
13 // 处理错误情况
14 console.log(error);
15 })
16 .finally(function () {
17 // 总是会执行
18 });
Ajax
Asynchronous JavaScript And XML(异步的 Javascript 和 XML)
Ajax 是一种思想,一种技术统称,xhr (XMLHttpRequest) fetch 都是实现 Ajax 的一种方式。
以 xhr 为例
1function ajax(url) {
2 const xhr = new XMLHttpRequest();
3 xhr.open("get", url, false);
4 xhr.onreadystatechange = function () {
5 // 异步回调函数
6 if (xhr.readyState === 4) {
7 if (xhr.status === 200) {
8 console.info("响应结果", xhr.response)
9 }
10 }
11 }
12 xhr.send(null);
13}
14
15ajax("https://www.krjojo.com/")