当使用Ajax请求时遇到互联网故障,向用户提供清晰的反馈非常重要。以下是完整的解决方案:
Ajax (Asynchronous JavaScript and XML) 是一种在不重新加载整个页面的情况下与服务器交换数据并更新部分网页的技术。当网络连接中断时,这些异步请求会失败。
if (!navigator.onLine) {
showOfflineMessage();
}
// 监听网络状态变化
window.addEventListener('online', () => {
hideOfflineMessage();
// 可选:自动重试失败的请求
});
window.addEventListener('offline', showOfflineMessage);
fetch('/api/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.catch(error => {
if (!navigator.onLine) {
showOfflineMessage();
} else {
showErrorMessage('请求失败: ' + error.message);
}
});
function showOfflineMessage() {
const offlineBanner = document.createElement('div');
offlineBanner.id = 'offline-banner';
offlineBanner.style.position = 'fixed';
offlineBanner.style.bottom = '0';
offlineBanner.style.left = '0';
offlineBanner.style.right = '0';
offlineBanner.style.backgroundColor = '#ff4444';
offlineBanner.style.color = 'white';
offlineBanner.style.padding = '10px';
offlineBanner.style.textAlign = 'center';
offlineBanner.style.zIndex = '1000';
offlineBanner.textContent = '⚠️ 网络连接已断开,请检查您的互联网连接';
document.body.appendChild(offlineBanner);
}
function hideOfflineMessage() {
const banner = document.getElementById('offline-banner');
if (banner) {
banner.remove();
}
}
// service-worker.js
self.addEventListener('fetch', event => {
event.respondWith(
fetch(event.request).catch(() => {
return new Response(
'<h1>离线模式</h1><p>您当前处于离线状态,部分功能可能不可用</p>',
{ headers: { 'Content-Type': 'text/html' } }
);
})
);
});
function showOfflineNotification() {
if (!('Notification' in window)) return;
if (Notification.permission === 'granted') {
new Notification('网络连接中断', {
body: '您已断开互联网连接',
icon: '/images/offline-icon.png'
});
} else if (Notification.permission !== 'denied') {
Notification.requestPermission().then(permission => {
if (permission === 'granted') {
new Notification('网络连接中断', {
body: '您已断开互联网连接',
icon: '/images/offline-icon.png'
});
}
});
}
}
<!DOCTYPE html>
<html>
<head>
<title>网络状态检测示例</title>
<style>
#offline-banner {
position: fixed;
bottom: 0;
left: 0;
right: 0;
background-color: #ff4444;
color: white;
padding: 10px;
text-align: center;
z-index: 1000;
display: none;
}
</style>
</head>
<body>
<div id="offline-banner">⚠️ 网络连接已断开,请检查您的互联网连接</div>
<button id="fetch-data">获取数据</button>
<div id="data-container"></div>
<script>
const offlineBanner = document.getElementById('offline-banner');
const fetchButton = document.getElementById('fetch-data');
const dataContainer = document.getElementById('data-container');
// 初始检查
if (!navigator.onLine) {
showOfflineMessage();
}
// 监听网络状态变化
window.addEventListener('online', () => {
hideOfflineMessage();
console.log('网络已恢复');
});
window.addEventListener('offline', showOfflineMessage);
fetchButton.addEventListener('click', fetchData);
function showOfflineMessage() {
offlineBanner.style.display = 'block';
}
function hideOfflineMessage() {
offlineBanner.style.display = 'none';
}
function fetchData() {
if (!navigator.onLine) {
showOfflineMessage();
return;
}
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) throw new Error('请求失败');
return response.json();
})
.then(data => {
dataContainer.innerHTML = `<pre>${JSON.stringify(data, null, 2)}</pre>`;
})
.catch(error => {
if (!navigator.onLine) {
showOfflineMessage();
} else {
dataContainer.innerHTML = `<p style="color:red">错误: ${error.message}</p>`;
}
});
}
</script>
</body>
</html>
通过以上方法,您可以有效地检测网络状态并在Ajax请求失败时向用户提供清晰的反馈。
没有搜到相关的文章