AJAX是一种异步JavaScript技术,实现局部页面更新而不刷新整个网页;现多用JSON而非XML;主流用fetch(),旧浏览器可选XMLHttpRequest;需注意错误处理、CORS、HTTPS及用户体验细节。
AJAX 是 Asynchronous JavaScript and XML 的缩写,指一种在不刷新整个网页的前提下,与服务器交换数据并更新部分页面内容的技术。虽然名字里有 XML,但现在更常用 JSON 格式传输数据。
传统网页提交表单会跳转或刷新整个页面;AJAX 则让浏览器在后台悄悄发请求,拿到响应后只改页面中需要变动的那一小块(比如一个列表、一段提示文字),体验更流畅。
推荐使用 内置的 fetch() API,简洁、基于 Promise,是当前标准做法。
fetch('/api/posts')
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error('请求失败:', err));
fetch('/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username: 'admin', password: '123' })
})
.then(res => res.json())
.then(result => console.log(result))
.catch(err => console.error(err));
如果必须支持 IE10 或更早版本,可用原生 XMLHttpRequest,但代码稍冗长:
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/data');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
} else {
console.error('请求出错');
}
}
};
xhr.send();
response.ok(fetch)或 status(XHR),HTTP 错误码(如 404、500)不会自动抛异常