Ajax请求

Ajax(Asynchronous JavaScript and XML)是早期实现异步通信的技术,虽然现在更多使用JSON,但仍广泛使用。

Ajax核心要素

XMLHttpRequest

原生API,提供完整的HTTP请求控制

异步处理

不阻塞UI,提升用户体验

数据格式

支持JSON、XML、HTML等多种格式

状态管理

readyState和status属性监控请求状态

实现示例

function ajaxRequest(url, method, data) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open(method, url, true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 300) { resolve(JSON.parse(xhr.response)); } else { reject(new Error('Request failed')); } }; xhr.onerror = function() { reject(new Error('Network error')); }; xhr.send(data ? JSON.stringify(data) : null); }); } // 使用示例 ajaxRequest('/api/users', 'GET') .then(data => console.log(data)) .catch(error => console.error(error));
← Backend Overview Backend Fetch →