JavaScript的核心功能XMLHttpRequest (XHR) 对象,允许开发者在不刷新页面的情况下异步地向服务器发送和接收数据,是构建动态交互式Web应用的基础,也是AJAX(异步JavaScript和XML)的核心。
XMLHttpRequest是JavaScript的API,用于通过HTTP请求与服务器通信,其主要优势在于:
要使用XHR,首先需要创建一个XMLHttpRequest对象的实例:
const xhr = new XMLHttpRequest();
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
xhr.onload = function () { if (xhr.status === 200) { console.log("响应数据:", xhr.responseText); } else { console.error("错误:", xhr.status, xhr.statusText); } };
xhr.send();
const xhr = new XMLHttpRequest(); xhr.open("GET", "https://jsonplaceholder.typicode.com/posts", true); xhr.onload = function () { if (xhr.status === 200) { console.log("数据获取成功:", JSON.parse(xhr.responseText)); } else { console.error("数据获取失败. 状态码:", xhr.status); } }; xhr.onerror = function () { console.error("网络错误导致请求失败。"); }; xhr.send();
XHR支持使用POST方法向服务器发送数据。
立即学习“Java免费学习笔记(深入)”;
示例:
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("数据保存成功:", JSON.parse(xhr.responseText)); } else { console.error("错误:", xhr.status); } }; const data = JSON.stringify({ title: "foo", body: "bar", userId: 1 }); xhr.send(data);
重要属性:
重要方法:
可以使用onreadystatechange事件监控XHR请求的进度。
示例:
xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { console.log("数据:", xhr.responseText); } };
尽管XHR仍然被广泛支持,但Fetch API提供了一种更现代化、基于Promise的HTTP请求方法。
Fetch示例:
fetch("https://jsonplaceholder.typicode.com/posts") .then(response => response.json()) .then(data => console.log("数据:", data)) .catch(error => console.error("错误:", error));
XMLHttpRequest是一种可靠且广泛支持的AJAX调用工具,但现代API (如Fetch或Axios等库) 通常因其简洁性和增强功能而更受欢迎。然而,理解XHR对于维护遗留代码和更深入地了解JavaScript异步通信至关重要。
作者:Abhay Singh Kathayat 全栈开发者,精通前端和后端技术,使用多种编程语言和框架构建高效、可扩展且用户友好的应用程序。 联系邮箱:kaashshorts28@gmail.com
以上就是掌握 XMLHttpRequest:JavaScript 中 AJAX 调用指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号