在JavaScript中,当用户离开页面(例如刷新、关闭标签页或导航到其他页面)时发送Ajax请求,通常可以使用navigator.sendBeacon
方法或者beforeunload
事件来实现。
beforeunload
事件。可以在这个事件中执行一些清理工作或者发送数据。navigator.sendBeacon
window.addEventListener('unload', function(event) {
const data = JSON.stringify({ userId: '123', action: 'leave' });
navigator.sendBeacon('/api/log', data);
});
beforeunload
事件window.addEventListener('beforeunload', function(event) {
const data = JSON.stringify({ userId: '123', action: 'leave' });
fetch('/api/log', {
method: 'POST',
body: data,
headers: {
'Content-Type': 'application/json'
},
keepalive: true // 确保请求在页面卸载时继续发送
});
});
navigator.sendBeacon
在现代浏览器中支持较好,但在一些旧版本浏览器中可能不支持。可以使用fetch
的keepalive
选项作为兼容性处理。navigator.sendBeacon
发送的数据量有限制,通常建议不要超过64KB。navigator.sendBeacon
或fetch
的keepalive
选项可以提高数据发送的成功率,但仍需注意数据大小限制。通过以上方法,可以在用户离开页面时可靠地发送Ajax请求,从而实现数据跟踪、统计等功能。
领取专属 10元无门槛券
手把手带您无忧上云