window.onbeforeunload Ajax请求的问题,Chrome浏览器 [英] window.onbeforeunload ajax request problem with Chrome
问题描述
我有一个处理,通过Ajax的远程控制一台机器的网页。当用户导航离开页面,我想从机器自动断开。因此,这里是code:
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();
}
断开连接功能,只需发送一个HTTP GET请求到PHP服务器端脚本,这确实断开的实际工作:
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() {
}
);
}
这在Firefox正常工作。但随着Chrome浏览器,Ajax请求是不是在所有发送。有一种不能接受的解决办法:增加警惕回调函数:
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.
可能有人告诉我,如果这是可以实现与Chrome浏览器?什么我完全合法的做在我看来。
Could somebody tell me if this is achievable with Chrome? What I'm doing looks completely legit to me.
谢谢
推荐答案
我有同样的问题,在Chrome浏览器是不发送AJAX请求到服务器在window.unload事件。
I was having the same problem, where Chrome was not sending the AJAX request to the server in the window.unload event.
我只能够得到它的工作,如果请求是同步的。我能够使用jQuery做到这一点,在异步属性设置为错误
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'
});
});
以上code为我工作在IE9,Chrome浏览器19.0.1084.52男,和Firefox 12。
The above code is working for me in IE9, Chrome 19.0.1084.52 m, and Firefox 12.
这篇关于window.onbeforeunload Ajax请求的问题,Chrome浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!