window.onbeforeunload 执行查询
我试图在用户离开页面时执行后查询。我正在使用的代码是
<script type="text/javascript">
window.onbeforeunload = function(){
var used = $('#identifier').val();
$.post('conversation.php?leave=true',{ud:used});
}
</script>
我在这里所做的事情有什么问题吗?我在 FF 错误控制台中得到的结果只是说其他不相关的函数/变量未定义(因为它们正在卸载)。对于我需要修复的问题有什么提示或指示吗?
I'm trying to perform a post query when the user leaves the page. The code I'm working with is
<script type="text/javascript">
window.onbeforeunload = function(){
var used = $('#identifier').val();
$.post('conversation.php?leave=true',{ud:used});
}
</script>
Is there anything wrong with what I'm doing here? The result I get in the FF error console is just saying that other non-related functions/variables are not defined (since they are unloading). Any tips or pointers for what I need to fix?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简单的答案是,您无法在
beforeunload
事件中可靠地进行异步 AJAX 调用,它很可能会在完成之前终止,因为浏览器垃圾收集页。您可以进行同步调用,如下所示:但请不要这样做,因为它会将您的用户困在页面中的时间超过需要的时间并阻止他们离开,导致负面的体验。请注意,这也会在执行时锁定浏览器,在任何可能的情况下都应避免
async: false
。The simple answer is you can't make an asynchronous AJAX call in the
beforeunload
event reliably, it'll very likely be terminated before it finished, as the browser garbage collects the page. You can make a synchronous call, like this:Please don't do this though, as it traps your user in the page for longer than needed and prevents them from leaving, resulting in a negative experience. Note that this also locks up the browser while it executes,
async: false
should be avoided in every case possible.