异步 JavaScript 和 XML - 创建动态网页的强大技术
AJAX(Asynchronous JavaScript and XML)是一种创建快速动态网页的技术。通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
在不阻塞用户界面的情况下与服务器交换数据,提供流畅的用户体验。
只更新页面需要变化的部分,减少数据传输量,提高响应速度。
创建响应式的用户界面,实现实时数据更新和交互功能。
下面是一个基本的 AJAX 请求示例,使用 XMLHttpRequest 对象:
// 创建 XMLHttpRequest 对象 const xhr = new XMLHttpRequest(); // 配置请求 xhr.open('GET', 'https://api.example.com/data', true); // 设置回调函数 xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { // 请求成功,处理响应数据 const response = JSON.parse(xhr.responseText); console.log(response); } }; // 发送请求 xhr.send();
XMLHttpRequest 对象的 readyState 属性表示请求的状态:
HTTP status 表示请求的结果状态:
Fetch API 是现代浏览器提供的更强大的 AJAX 接口,使用 Promise 处理异步操作:
// 使用 Fetch API fetch('https://api.example.com/data') .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .then(data => { console.log(data); }) .catch(error => { console.error('There was a problem with the fetch operation:', error); }); // 使用 async/await 语法 async function fetchData() { try { const response = await fetch('https://api.example.com/data'); const data = await response.json(); console.log(data); } catch (error) { console.error('Error:', error); } }
POST 请求用于向服务器发送数据:
// 发送 JSON 数据 const data = { name: 'John', email: 'john@example.com' }; fetch('https://api.example.com/users', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => console.log('Success:', data)) .catch((error) => console.error('Error:', error));
股票价格、天气预报等实时数据更新,无需刷新页面。
即时消息发送和接收,实现实时通信功能。
购物车更新、订单提交、支付处理等。
实时验证用户输入,提供即时反馈。
这是一个常见的 AJAX 应用:搜索时显示建议列表。
const searchInput = document.getElementById('search'); const suggestions = document.getElementById('suggestions'); searchInput.addEventListener('input', function() { const query = this.value; if (query.length < 2) { suggestions.innerHTML = ''; return; } fetch(`https://api.example.com/suggest?q=${encodeURIComponent(query)}`) .then(response => response.json()) .then(data => { suggestions.innerHTML = data.map(item => `${item}` ).join(''); }); });