AJAX (Asynchronous JavaScript and XML) 是一种在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页的技术。它允许网页通过JavaScript异步地向服务器发送请求和接收响应。
// 创建XMLHttpRequest对象
var xhr = new XMLHttpRequest();
// 配置请求
xhr.open('GET', 'https://api.example.com/data', true);
// 设置回调函数
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// 请求成功,处理响应数据
var response = JSON.parse(xhr.responseText);
console.log(response);
document.getElementById('result').innerHTML = response.data;
} else if (xhr.readyState === 4) {
// 请求失败
console.error('请求失败: ' + xhr.status);
}
};
// 发送请求
xhr.send();
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json();
})
.then(data => {
console.log(data);
document.getElementById('result').innerHTML = data.message;
})
.catch(error => {
console.error('请求失败:', error);
});
axios.get('https://api.example.com/data')
.then(function (response) {
console.log(response.data);
document.getElementById('result').innerHTML = response.data.message;
})
.catch(function (error) {
console.error('请求失败:', error);
});
原因:浏览器同源策略限制
解决方案:
原因:网络延迟或服务器响应慢
解决方案:
// 原生AJAX设置超时
xhr.timeout = 5000; // 5秒超时
xhr.ontimeout = function() {
console.error('请求超时');
};
// Fetch API使用AbortController
const controller = new AbortController();
const signal = controller.signal;
setTimeout(() => controller.abort(), 5000);
fetch(url, { signal })
.then(response => response.json())
.catch(err => {
if (err.name === 'AbortError') {
console.error('请求超时');
}
});
原因:服务器返回的数据格式与预期不符
解决方案:
// 明确指定期望的响应类型
xhr.responseType = 'json';
// 或手动验证数据格式
fetch(url)
.then(response => response.json())
.then(data => {
if (!data || typeof data !== 'object') {
throw new Error('无效的数据格式');
}
// 处理数据
});
解决方案:
// 使用Promise.all处理多个并行请求
Promise.all([
fetch('/api/users'),
fetch('/api/posts')
])
.then(responses => Promise.all(responses.map(res => res.json())))
.then(data => {
const users = data[0];
const posts = data[1];
// 处理数据
})
.catch(error => console.error(error));
解决方案:
AJAX是现代Web开发的核心技术之一,合理使用可以显著提升应用性能和用户体验。