AJAX and user leaving a page

前端 未结 4 1664
心在旅途
心在旅途 2021-02-04 05:48

I\'m working on a chat and I\'m trying to figure out how I can detect that the user has left the page or not. Almost everything is being handled by the database to avoid the fro

4条回答
  •  面向向阳花
    2021-02-04 06:15

    Try this:

    $(window).unload(function(){
        $.ajax({
            type: 'POST',
            url: 'script.php',
            async:false,
            data: {key_leave:"289583002"}
        });
    });
    

    Note the async:false, that way the browser waits for the request to finish.

    Using $.post is asynchronous, so the request may not be quick enough before the browser stops executing the script.

提交回复
热议问题