掌握 XMLHttpRequest:JavaScript 中的 AJAX 调用指南
用于 AJAX 调用的 XMLHttpRequest
**XMLHttpRequest (XHR)** 对象是 JavaScript 的核心功能,可让您从服务器异步发送和接收数据,而无需刷新网页。它构成了 AJAX(异步 JavaScript 和 XML)的基础,可实现动态和交互式 Web 应用程序。
1.什么是XMLHttpRequest?
**XMLHttpRequest** 是 JavaScript 中的一个 API,它通过 HTTP 请求促进与服务器的通信。它支持:
2.创建 XMLHttpRequest 对象
要使用 XHR,请创建 `XMLHttpRequest` 对象的实例:
const xhr = new XMLHttpRequest();
3. 进行 XHR 调用的步骤
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);xhr.onload = function () {
if (xhr.status === 200) {
console.log("Response:", xhr.responseText);
} else {
console.error("Error:", xhr.status, xhr.statusText);
}
};xhr.send();
4.完整示例:GET 请求
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts", true);
xhr.onload = function () {
if (xhr.status === 200) {
console.log("Data retrieved:", JSON.parse(xhr.responseText));
} else {
console.error("Failed to fetch data. Status:", xhr.status);
}
};
xhr.onerror = function () {
console.error("Request failed due to a network error.");
};
xhr.send();5. 使用 POST 请求发送数据
XHR 允许使用 POST 向服务器发送数据。
**例子:**
const xhr = new XMLHttpRequest();
xhr.open("POST", "https://jsonplaceholder.typicode.com/posts", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function () {
if (xhr.status === 201) {
console.log("Data saved:", JSON.parse(xhr.responseText));
} else {
console.error("Error:", xhr.status);
}
};
const data = JSON.stringify({
title: "foo",
body: "bar",
userId: 1
});
xhr.send(data);6. XHR 的属性和方法
主要属性:
主要方法:
7. 处理响应状态
您可以使用“onreadystatechange”事件来监视 XHR 请求的进度。
**例子:**
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log("Data:", xhr.responseText);
}
};8.使用 XHR 的优点
9.XHR 的局限性
10. 现代替代方案:Fetch API
虽然 XHR 仍然受到广泛支持,但 Fetch API 提供了一种基于承诺的现代方法来发出 HTTP 请求。
**获取示例:**
fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => response.json())
.then(data => console.log("Data:", data))
.catch(error => console.error("Error:", error));11. 结论
**XMLHttpRequest** 是一种可靠且支持良好的 AJAX 调用工具,但现代 API(如 `fetch`)或库(如 Axios)通常因其简单性和增强功能而更受青睐。然而,了解 XHR 对于维护遗留代码和深入了解 JavaScript 中异步通信的工作原理至关重要。