window.onbeforeunload performing query

自闭症网瘾萝莉.ら 提交于 2020-01-03 20:33:06

问题


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?


回答1:


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
});

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.



来源:https://stackoverflow.com/questions/4235437/window-onbeforeunload-performing-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!