window.onbeforeunload执行查询 [英] window.onbeforeunload performing query

查看:89
本文介绍了window.onbeforeunload执行查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在用户离开页面时执行帖子查询。我正在使用的代码是

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>

我在这里做什么有什么问题吗?我在FF错误控制台中得到的结果只是说没有定义其他非相关函数/变量(因为它们正在卸载)。我需要解决的任何提示或指示?

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?

推荐答案

简单的答案是你无法进行异步AJAX调用可靠地 beforeunload 事件,它将非常在它完成之前终止,因为浏览器垃圾收集页面。你可以进行同步通话,如下所示:

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:

$.ajax({ 
  type: "POST", 
  url: 'conversation.php?leave=true', 
  data:{ud:used}, 
  async: false
});

不要这样做,因为它会抓住你的用户页面持续时间超过需要并阻止它们离开,从而导致负面体验。请注意,这也是在执行时锁定浏览器,在每种情况下都应该避免 async:false

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.

这篇关于window.onbeforeunload执行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆