功能点 | XHR | Fetch |
---|
基本的请求能力 | ✔️ | ✔️ |
基本的获取响应能力 | ✔️ | ✔️ |
监控请求进度 | ✔️ | ❌ |
监控响应进度 | ✔️ | ✔️ |
Service Worker中是否可用 | ❌ | ✔️ |
控制cookie的携带 | ❌ | ✔️ |
控制重定向 | ❌ | ✔️ |
请求取消 | ✔️ | ✔️ |
自定义referrer | ❌ | ✔️ |
流 | ❌ | ✔️ |
API风格 | Event | Promise |
活跃度 | 停止更新 | 不断更新 |
一、XHR的基本使用
// 创建新的 XMLHttpRequest 对象
var xhr = new XMLHttpRequest();
// 设置回调函数,处理响应数据
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error("Request failed. Status code:", xhr.status);
}
};
// 打开连接
xhr.open("GET", "url");
// 发送请求
xhr.send();
二、Fetch的基本使用
// 使用 Fetch API 发送 GET 请求
fetch("url")
.then(function(response) {
// 处理响应
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.text();
})
.then(function(text) {
// 输出响应文本
console.log(text);
})
.catch(function(error) {
// 处理错误
console.error("Fetch error:", error);
});