AJAX和用户离开网页网页、用户、AJAX

2023-09-11 22:30:41 作者:夏末的晨曦

我正在聊天,我试图找出如何我可以检测到用户离开网页或没有。几乎一切都被由数据库处理,以避免搞乱前端。

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 front end from messing up.

所以,我想要做的是,一旦页供任何原因(窗口关闭,要到另一个页面,点击一个链接,等等)一个人离开,所以我可以更新之前Ajax调用将被解雇数据库。

So what I'm trying to do is once the page is left for any reason (window closed, going to another page, clicking a link, etc.) an ajax call will be fired before a person leaves so I can update the database.

这是我已经试过:

$(window).unload(function(){
      $.post("script.php",{key_leave:"289583002"});
});

有关一些奇怪的原因,这是行不通的,我已经检查了PHP的code,并能正常工作。有什么建议?

For some odd reason, it wouldn't work, and I've checked the php code, and it works fine. Any suggestions?

推荐答案

试试这个:

$(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.

 
精彩推荐
图片推荐