Javascript 简明教程
JavaScript - Ajax
异步 JavaScript 和 XML (Ajax) 是一种 Web 开发技术:它支持服务器和网页之间的动态、交互式通信,而无需完全重新加载页面。描述符“异步”强调数据交换可以在后台发生,而无需中断用户体验。与其静候整个页面刷新;Ajax 增强了对网页特定部分的实时更新,从而产生更无缝、响应更快的界面。
Asynchronous JavaScript and XML (Ajax) represents a web development technique: it enables dynamic, interactive communication between server and webpage without necessitating complete page reload. The descriptor "asynchronous" underlines that data exchanges can occur in the background, independent of user experience disruption. Rather than idly awaiting full-page refreshment; Ajax empowers real-time updates on specific sections of a webpage, thus yielding an interface that is more seamless and responsive.
How Ajax works?
在启用动态更新中发挥核心作用的,无需完全重新加载页面,是在 JavaScript 的 Ajax 功能中的 XMLHttpRequest 对象。这个特殊进程允许服务器和网页之间进行异步通信。服务器在收到该对象发送的请求后使用数据(通常是 JSON 或 XML 格式)来响应。处理数据是 JavaScript 的任务;它实时更新网页的特定部分。异步特性对于现代 Web 开发来说是至关重要的,它确保这些操作在后台进行,从而通过允许以异步方式获取和发送数据来提高交互性。
The central role in enabling dynamic updates, without the necessity of a full page reload, belongs to the XMLHttpRequest object within JavaScript’s Ajax functionality. This particular process allows for asynchronous communication between server and web page. The server responds with data, usually in JSON or XML format when receiving a request sent by this object. Processing this data is the task of JavaScript; it updates specific portions of the webpage in real-time. The asynchronous nature which is a critical feature for modern web development ensures these operations occur unobtrusively in background, thereby enhancing interactivity by allowing data to be fetched and sent asynchronously.
在此处,我们将探索 Ajax 以获得对它的更深层次的理解。
Here, we will to explore Ajax to get a deeper understanding of it.
有 4 种方法用于对 Ajax 进行调用或在 JavaScript 中实现 Ajax,这 4 种方法如下:
There are 4 approaches to make Ajax calls or to implement Ajax in JavaScript and they are:
-
XMLHttpRequest (Older Approach)
-
Fetch API (Modern Approach)
-
Axios (Library for HTTP Requests)
-
jQuery Ajax
在所有用于理解示例的示例中,我们都将使用 JSONPlaceholder。
We will be using JSONPlaceholder in all the examples for understanding purposes.
JSONPlaceholder 是一个开源的模拟 REST API 提供程序,可让开发人员测试其原型应用程序。它为多个资源(例如用户、帖子、评论等)返回虚假/虚拟数据。JSONPlaceholder 的 API 端点可通过 HTTP 请求实现,并且这些端点将模拟真实 API 的本质,而无需身份验证。我们在本文中的目标是使用这些 API/端点来理解 Javascript-Ajax。
JSONPlaceholder is an open-source and simulated REST API provider which lets developers test their prototype applications. It returns fake/dummy data for various resources like users, posts, comments etc. The API endpoints of JSONPlaceholder can be made using HTTP requests and they will be mimicking the nature of real APIs without any need for authentication. Our goal here is to use these APIs/endpoints to under Javascript-Ajax.
Using XMLHttpRequest
使用 XMLHttpRequest 的原生 JavaScript 方法代表了该异步请求最老的方法。它依赖于 XMLHttpRequest 对象来创建和发送 HTTP 请求。该方法涉及设置回调函数来处理请求的各种状态,使其适用于较简单的场景。但是,与更现代的方法相比,它具有一些局限性。
The Native JavaScript approach using XMLHttpRequest represents the oldest method for asynchronous requests. It relies on the XMLHttpRequest object to create and send HTTP requests. This method involves setting up callback functions to handle various states of the request, making it suitable for simpler scenarios. However, it has some limitations compared to more modern approaches.
Example
<!DOCTYPE html>
<html lang="en">
<body>
<p>Native XMLHttpRequest Example</p>
<button onclick="nativeAjax()">Make Request</button>
<pre id="result"></pre>
<script>
function nativeAjax() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/users/2', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var responseData = JSON.stringify(JSON.parse(xhr.responseText), null, 2);
document.getElementById('result').innerText = 'Native XMLHttpRequest:\n' + responseData;
}
};
xhr.send();
}
</script>
</body>
</html>
Using Fetch API
Fetch API 是 XMLHttpRequest 的现代替代方法,它提供了一种更加直接、功能更强大的语法;它返回 Promise,从而增强了对异步操作的直观处理。支持广泛的 HTTP 方法和标头:这为开发人员提供了一种更简洁、更简洁的方法来进行异步请求。当代 JavaScript 应用程序通常更喜欢它,因为它清晰且易于使用。
Presenting a modern alternative to XMLHttpRequest, the Fetch API offers a more straightforward and powerful syntax; it returns Promises thus enhancing the intuitive handling of asynchronous operations. Supporting an extensive array of HTTP methods and headers: this provides developers with a cleaner, concise method for making asynchronous requests. Contemporary JavaScript applications often prefer it for its clarity and ease of use.
Example
<!DOCTYPE html>
<html>
<body>
<h1>Fetch API Example</h1>
<button onclick="fetchApi()">Make Request</button>
<pre id="result"></pre>
<script>
function fetchApi() {
fetch('https://jsonplaceholder.typicode.com/users/3')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
var formattedData = JSON.stringify(data, null, 2);
document.getElementById('result').innerText = 'Fetch API:\n' + formattedData;
})
.catch(error => {
document.getElementById('result').innerText = 'Fetch API Error: ' + error.message;
});
}
</script>
</body>
</html>
Using Axios
专为发出 HTTP 请求而设计的 Axios 成为流行的 JavaScript 库。其流行在很大程度上归功于其简洁明确的语法:在 Promise 的基础上构建;此外,它还拥有自动 JSON 数据转换支持功能,使其区别于该领域的其他库。Axios 不仅提供基本功能,还提供了高级功能,例如请求和响应拦截器,这是一个在现代 Web 开发环境中管理 AJAX 操作的强大选择。
Designed for making HTTP requests, Axios emerges as a popular JavaScript library. Its popularity is largely due to its clean and concise syntax: built on Promises; furthermore, it boasts automatic JSON data transformation support features that set it apart from other libraries in the field. Offering more than just basic functionality, Axios presents advanced features such as request and response interceptors, a robust selection for managing AJAX operations within the context of modern web development environment.
Example
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
<h1>Axios Example</h1>
<button onclick="axiosExample()">Make Request</button>
<pre id="result3"></pre>
<script>
function axiosExample() {
axios.get('https://jsonplaceholder.typicode.com/users/5')
.then(response => {
var formattedData = JSON.stringify(response.data, null, 2);
document.getElementById('result3').innerText = 'Axios:\n' + formattedData;
})
.catch(error => {
document.getElementById('result3').innerText = 'Axios Error: ' + error.message;
});
}
</script>
</body>
</html>
Using Ajax jQuery
jQuery 中的 $.ajax 方法简化了 AJAX 请求流程:它以前是一种流行的方法;然而,随着现代 JavaScript 的兴起,它的使用量已有所下降。jQuery Ajax 提供了一致且跨浏览器兼容的界面,因此对于由于它提供的这些优势而已经使用或需要 jQuery 特定功能的项目,它仍然适用。但是,对于新项目,现代替代方法可能是首选。
The $.ajax method in jQuery simplifies the AJAX request process: a popular approach previously; however, its usage has waned alongside modern JavaScript’s ascent. Offering an interface that is both consistent and cross-browser compatible, jQuery Ajax remains suitable for projects already using or needing specific features of jQuery due to these advantages it presents. However, for new projects, modern alternatives may be preferred.
Example
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>
<h1>jQuery Ajax Example</h1>
<button onclick="jqueryAjax()">Make Request</button>
<pre id="result4"></pre>
<script>
function jqueryAjax() {
$.ajax({
url: 'https://jsonplaceholder.typicode.com/users/7',
method: 'GET',
dataType: 'json',
success: function (data) {
var formattedData = JSON.stringify(data, null, 2);
document.getElementById('result4').innerText = 'jQuery Ajax:\n' + formattedData;
},
error: function (xhr, status, error) {
document.getElementById('result4').innerText = 'jQuery Ajax Error: ' + error;
}
});
}
</script>
</body>
</html>
Ajax Use Cases
在实际场景中,开发人员通常采用 Ajax 来创建具有响应性和交互性的 Web 应用程序。一个相关的示例:社交媒体平台;在这里,由于 Ajax,用户可以在后台添加或加载新评论,而不必刷新整个页面。动态更新确保了顺畅和不间断的用户体验,允许个人无缝地参与内容和彼此互动。此过程产生了一个更加响应和引人入胜的平台;它放大了用户交互,从而提高了满意度。
In real-world scenarios, developers commonly employ Ajax to create web applications that are both responsive and interactive. A pertinent example: a social media platform; here, users have the ability - thanks to Ajax, to add or load new comments in the background without needing an entire page refresh. Dynamic updating ensures a user experience that is smooth and uninterrupted, permitting individuals to engage with content and one another seamlessly. This process yields a platform more responsive and engaging; it amplifies user interaction thus enhancing satisfaction.
利用 Ajax 增强用户体验的知名公司包括 Google(Gmail、地图)、Facebook、Twitter、Amazon、Netflix、GitHub、LinkedIn、YouTube、Microsoft Office Online 和 Uber。Ajax 用于在各自平台上进行实时更新、动态内容加载和无缝交互。
Prominent companies utilizing Ajax for enhanced user experiences include Google (Gmail, Maps), Facebook, Twitter, Amazon, Netflix, GitHub, LinkedIn, YouTube, Microsoft Office Online, and Uber. Ajax is employed for real-time updates, dynamic content loading, and seamless interactions on their respective platforms.