window.onbeforeunload在Chrome中加载ajax请求 [英] window.onbeforeunload ajax request in Chrome

查看:145
本文介绍了window.onbeforeunload在Chrome中加载ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过Ajax处理机器远程控制的网页。当用户离开页面时,我想自动从机器上断开连接。所以这里是代码:

pre $ window.onbeforeunload = function(){
bas_disconnect_only();


$


断开连接函数只需发送一个HTTP GET请求到一个PHP服务器端脚本,它实际上是断开连接的工作:

$ p $ function bas_disconnect_only(){
var xhr = bas_send_request(req = 10 ,function(){
});
}

这在FireFox中正常工作。但对于Chrome,ajax请求根本不会被发送。有一种不可接受的解决方法:向回调函数添加警报:

 函数bas_disconnect_only(){
var xhr = bas_send_request (req = 10,function(){
alert(您被自动断开连接。);
});
}

在添加警报呼叫后,请求将成功发送。但是,正如你所看到的,这根本不是一项真正的工作。



有人能告诉我这是否可以通过Chrome实现吗?我在做什么看起来完全合法。



谢谢,

我遇到同样的问题,Chrome并未在window.unload事件中向服务器发送AJAX请求。



我只能得到它如果请求是同步的,则工作。我可以通过Jquery完成此操作,并将异步属性设置为 false

  $(window).unload(function(){
$ .ajax({
类型:'GET',
async:false,
url:'SomeUrl .com?id = 123'
});
});

以上代码适用于IE9,Chrome 19.0.1084.52 m和Firefox 12。 / p>

I have a web page that handles remote control of a machine through Ajax. When user navigate away from the page, I'd like to automatically disconnect from the machine. So here is the code:

window.onbeforeunload = function () {
  bas_disconnect_only();
}

The disconnection function simply send a HTTP GET request to a PHP server side script, which does the actual work of disconnecting:

function bas_disconnect_only () {
   var xhr = bas_send_request("req=10", function () {
   });
}

This works fine in FireFox. But with Chrome, the ajax request is not sent at all. There is a unacceptable workaround: adding alert to the callback function:

function bas_disconnect_only () {
   var xhr = bas_send_request("req=10", function () {
     alert("You're been automatically disconnected.");
   });
}

After adding the alert call, the request would be sent successfully. But as you can see, it's not really a work around at all.

Could somebody tell me if this is achievable with Chrome? What I'm doing looks completely legit to me.

Thanks,

解决方案

I was having the same problem, where Chrome was not sending the AJAX request to the server in the window.unload event.

I was only able to get it to work if the request was synchronous. I was able to do this with Jquery and setting the async property to false:

$(window).unload(function () {
   $.ajax({
     type: 'GET',
     async: false,
     url: 'SomeUrl.com?id=123'
   });
});

The above code is working for me in IE9, Chrome 19.0.1084.52 m, and Firefox 12.

这篇关于window.onbeforeunload在Chrome中加载ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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