常规HTTP调用是传统的网页请求方式,当用户与网页交互时,浏览器会向服务器发送请求,服务器返回完整的HTML页面,浏览器会重新加载整个页面。
AJAX (Asynchronous JavaScript and XML) 是一种在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页内容的技术。
| 特性 | 常规HTTP调用 | AJAX | |------|------------|------| | 交互方式 | 同步(默认) | 异步 | | 页面刷新 | 整页刷新 | 局部更新 | | 用户体验 | 较差(页面闪烁) | 流畅 | | 带宽使用 | 较高(传输整个页面) | 较低(只传输必要数据) | | 实现方式 | 表单提交/链接点击 | JavaScript XMLHttpRequest或Fetch API |
const xhr = new XMLHttpRequest();
xhr.open('GET', 'api/data', true);
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
fetch('api/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
$.ajax({
url: 'api/data',
type: 'GET',
success: function(data) {
console.log(data);
}
});
<form action="/submit" method="POST">
<input type="text" name="username">
<button type="submit">提交</button>
</form>
原因: 浏览器的同源策略限制 解决方案:
原因: 异步请求未正确处理响应 解决方案:
// 确保在响应处理中更新UI
fetch('api/data')
.then(response => response.json())
.then(data => {
document.getElementById('result').innerText = data.message;
});
原因: 整页刷新 解决方案:
原因: 搜索引擎爬虫可能无法执行JavaScript 解决方案:
随着Web技术的发展,Fetch API逐渐取代传统的XHR,而新的技术如WebSockets(全双工通信)和Server-Sent Events(服务器推送)为特定场景提供了更好的解决方案。GraphQL也提供了一种更灵活的API查询方式,常与AJAX结合使用。
没有搜到相关的文章