AJAX是通过XMLHttpRequest或fetch实现异步通信以局部更新页面的技术,推荐使用基于Promise的fetch配合async/await,并注意loading提示、防重复提交、请求取消和CORS跨域处理。
AJAX(Asynchronous JavaScript and XML)是一种在不重新加载整个网页的前提下,与服务器交换数据并更新部分页面内容的技术。它的核心是异步通信,用户操作时页面不“闪退”、不跳转,体验更流畅。
现代浏览器都内置了 XMLHttpRequest(简称 XHR),它是实现 AJAX 的底层接口。虽然名字里有 XML,但现在更多用来传输 JSON 数据。
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/data', true);(第三个参数 true 表示异步)xhr.onload = function() { if (xhr.status === 200) { console.log(xhr.responseText); } };
xhr.send();
fetch 是较新的标准,基于 Promise,语法更清晰,是目前推荐的主流方式。
fetch('/api/user').then(res => res
.json()).then(data => console.log(data));
fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'admin', password: '123' })
}).then(res => res.json()).then(data => console.log(data));
credentials: 'include'
配合 async/await,可以把 Promise 链式调用写成类似同步的风格,减少嵌套,便于错误处理。
async function loadUserData() {
try {
const res = await fetch('/api/profile');
const data = await res.json();
document.getElementById('name').textContent = data.name;
} catch (err) {
console.error('请求失败:', err);
}
}
apiGet(url) 或 apiPost(url, data)
光能发请求还不够,真实项目中这几个细节常被忽略:
AbortController)