AJAX (Asynchronous JavaScript and XML) 是一种在不重新加载整个页面的情况下与服务器交换数据并更新部分网页的技术。onload
事件是当页面完全加载(包括所有依赖资源如图片和样式表)后触发的事件。
XMLHttpRequest
对象原因:
解决方案:
window.onload = function() {
// 使用原生 XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open('GET', 'your-api-endpoint', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
}
};
xhr.send();
// 或者使用更现代的 Fetch API
fetch('your-api-endpoint')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
};
原因:
解决方案:
原因:
解决方案:
document.addEventListener('DOMContentLoaded', function() {
// 更轻量级的替代方案,不需要等待所有资源加载
loadData();
});
function loadData() {
// 显示加载状态
document.getElementById('loading').style.display = 'block';
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
// 处理数据
renderData(data);
// 隐藏加载状态
document.getElementById('loading').style.display = 'none';
})
.catch(error => {
console.error('Fetch error:', error);
document.getElementById('error').style.display = 'block';
document.getElementById('loading').style.display = 'none';
});
}
function renderData(data) {
// 更新DOM
const container = document.getElementById('data-container');
container.innerHTML = data.map(item => `<div>${item.name}</div>`).join('');
}
没有搜到相关的文章