当用户关闭浏览器窗口时发送ajax [英] Sending ajax when user closes browser window

查看:47
本文介绍了当用户关闭浏览器窗口时发送ajax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的主要目标和实际情况::如果两个用户共享相同的凭据,则第二个用户只有在第一个已经登录并退出系统后才能登录系统./p>

实际上,我想在用户关闭浏览器窗口时在服务器数据库上设置 login_flag = 0 .我通过google搜索并确定要通过

发送ajax请求

  $(window).on('unload',function(){//这里是ajax,带有async:false}); 

  $(window).on('beforeunload',function(){//这里是ajax,带有async:false}); 

一切正常.但是在Chrome中,它会记录以下消息:

由于以下原因,不赞成在主线程上使用同步XMLHttpRequest:它对最终用户体验的有害影响.要获得更多帮助,检查 http://xhr.spec.whatwg.org/.

我再次用谷歌搜索相同的内容,得知不鼓励在卸载事件上使用Ajax,并从此处

简而言之,它们反对将Ajax与 window.unload window.beforeUnload 方法一起用于 async:false .如果我从Ajax中删除 async 参数,则它无法正常工作.

如果用户要关闭浏览器窗口并在服务器端进行一些活动,正确的方法是什么?

解决方案

我记得在类似的情况下,一旦用户关闭窗口,我需要在服务器端执行操作.但是,我的研究得出的结论与您的结论相同,因此不建议在窗口卸载事件中使用任何类型的Ajax调用.因此,我的最终方法是在窗口卸载事件中在客户端上设置特定的Cookie,然后当同一用户访问该页面时,才执行所需的操作,并从服务器端删除了Cookie.

我知道这并不能完全同时执行操作,但这是对我有用的最佳方法.

My Main GOAL and actual scenario: If two users share the same credentials, then the second user can not login into the system until the first one who is already logged in, log outs system.

Actually I want to set login_flag=0 on server database, when user closes the browser window. I googled and figured out to send an ajax request before either by

$(window).on('unload', function(){ // ajax here with async:false });

or

$(window).on('beforeunload', function(){ // ajax here with async:false });

It's working fine. But in Chrome, it logs the following message:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.

I have googled again for the same and came to know that it is discouraging to use Ajax on unload event, and found following details from here

in short, they are against the use of ajax with async:false with window.unload or window.beforeUnload method. If I remove async param from Ajax, then it's not working as intended.

What is the right approach if I want to do some activity on server side if user closes browser window?

解决方案

I remember to be in a similar situation once where I needed to perform an action on server side once user closed the window. However, my research came to same conclusion as yours that is discouraged to use any type of ajax call on window unload events. So, my final approach was to set a specific Cookie on client side in the window unload event, and when the same user visited that page, only then I performed my required action and deleted the cookie from server side.

I know this is not exactly performing the action at the same time but that was the best approach which worked for me.

这篇关于当用户关闭浏览器窗口时发送ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆