window.onbeforeunload performing query
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 use开发者_C百科d = $('#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?
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.
精彩评论