javascript AJAX 和用户离开页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10272561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AJAX and user leaving a page
提问by Majo0od
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.
我正在聊天,我想弄清楚如何检测用户是否离开了页面。几乎所有事情都由数据库处理,以避免前端搞砸。
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.
因此,我想要做的是,一旦页面因任何原因(窗口关闭、转到另一个页面、单击链接等)离开,就会在一个人离开之前触发 ajax 调用,以便我可以更新数据库。
This is what I've tried:
这是我尝试过的:
$(window).unload(function(){
$.post("script.php",{key_leave:"289583002"});
});
For some odd reason, it wouldn't work, and I've checked the php code, and it works fine. Any suggestions?
出于某种奇怪的原因,它不起作用,我检查了 php 代码,它运行良好。有什么建议?
回答by stewe
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.
请注意async:false
,浏览器等待请求完成的方式。
Using $.post
is asynchronous, so the request may not be quick enough before the browser stops executing the script.
使用$.post
是异步的,因此在浏览器停止执行脚本之前请求可能不够快。
回答by Parv Sharma
This isn't the correct way of doing this... Suppose the OS just hangs or something happens in the browsers process then this event wont be fired. And you will never ever know when the user has left, showing him/her online ever after he/she has disconnected. Instead of this, what you can do is.
这不是执行此操作的正确方法...假设操作系统只是挂起或浏览器进程中发生了某些事情,则不会触发此事件。你永远不会知道用户什么时候离开,在他/她断开连接后显示他/她在线。取而代之的是,您可以做的是。
- Try connecting a socket so that you can know the user is disconnected when the socket is disconnected
- You can send a request to the server (say after every 1 sec) so that you can know that the user is still connected. If you didn't receive the request - even after 2 secconds - disconnect the user.
- 尝试连接一个socket,这样在socket断开的时候就可以知道用户已经断开了
- 您可以向服务器发送请求(比如每 1 秒后),以便您知道用户仍然处于连接状态。如果您没有收到请求 - 即使在 2 秒后 - 断开用户连接。
回答by Milan Jaric
Try to add popup (prompt("leaving so early?")) after $.post. It may work. Tho it may be bad user experience. :)
尝试在 $.post 后添加弹出窗口(提示(“这么早离开?”))。它可能会起作用。这可能是糟糕的用户体验。:)
回答by Edesa
This is related to the answer above. https://stackoverflow.com/a/10272651/1306144
这与上面的答案有关。https://stackoverflow.com/a/10272651/1306144
This will execute the ajax call every 1 sec. (1000)
这将每 1 秒执行一次 ajax 调用。(1000)
function callEveryOneSec() {
$jx.ajax({}); // your ajax call
}
setInterval(callEveryOneSec, 1000);