PHP JavaScript?当用户关闭页面或浏览器时执行某些操作
基本上,我想通过更新我的 MySQL 数据库将用户设置为“离线”,并可能在他们关闭浏览器或 页。
我见过一个网站是这样做的。
谁能解释一下它是如何完成的并发布一个例子吗?
提前谢谢您。
Possible Duplicate:
How can I destroy sessions if user closes the browser window or navigates away from page in php?
Basically I want to set my users to "Offline" by updating my MySQL DB and possibly end their session when they close their browser or the page.
I have seen a website that does this.
Can anyone explain how its done and post an example please?
Thank you in advanced.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当页面关闭或导航离开时,您可以执行某些操作的唯一方法是将事件处理程序附加到卸载事件,如 Rocket 建议的那样。但是,您不应该依赖此事件来触发,因为很多事情可能会阻止它。浏览器可能会停止它,以便将其资源集中在其他任务上,用户可能会失去连接,浏览器可能会被终止,等等。
跟踪用户和会话的最可靠方法是让他们将 keepAlive 消息发送到服务器以给定的时间间隔。然后您就会知道用户在给定时间戳和 keepAlive 消息间隔之间的某个时间离开了。
在服务器上,您可以遍历一段时间内未保持活动状态的会话并执行您需要的任何操作。
但是,如果您只需要创建一些很酷的“注销”效果,则不需要这种方法。
The only way you can do something when the page is closed or navigated away from is to attach an event handler to the unload event, as Rocket suggests. However, you shouldn't rely on this event to trigger, as a lot of things may prevent it. The browser may stop it on order to focus it's resources on other tasks, the user may loose it's connection, the browser may be terminated, etc.
The most reliable way to keep track of users and session is to have them send keepAlive messages to the server at a given interval. Then you'll know that the user left sometime between a given timestamp and the interval of the keepAlive message.
On the server, you can then traverse the sessions which has not been kept alive for a while and perform any operation you need.
However, this approach won't be necessary if you only need to create some cool "logging off"-effect.
我将使用 jQuery 来执行此任务..类似这样并使用上面提到的 window.onunload :
I would use jQuery to perform this task.. something like this and using the window.onunload as mentioned above:
您可以使用
window.onunload
来触发 AJAX当用户离开页面/关闭选项卡时调用。编辑:我建议在单击链接时设置一个变量,以便仅在用户离开页面时运行。
使用 jQuery,可以这样完成:
You can use
window.onunload
to fire an AJAX call when the user leaves the page/closes the tab.EDIT: I suggest setting a variable when clicking on links, so that this only runs when the user leaves the page.
Using jQuery, it can be done like this: