卸载时通过 Ajax 运行 PHP
我试图在用户离开页面时运行一个 php 脚本。这就是我目前正在使用的:
function unload(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
window.location = "unsupported.html";
return false;
}
}
}
ajaxRequest.open("GET", "ajax/cancelMatch.php", true);
ajaxRequest.send(null);
}
通过FireBug,看起来它正在调用ajaxRequest对象的open函数,但是PHP没有运行!这是否与它在页面卸载时调用它有关?
另外,我发现了一个名为 onbeforeunload 的事件,但我不知道如何让它工作(如果它仍然可用)。
I'm trying to have a php script run when the user navigates away from the page. This is what I'm using currently:
function unload(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
window.location = "unsupported.html";
return false;
}
}
}
ajaxRequest.open("GET", "ajax/cancelMatch.php", true);
ajaxRequest.send(null);
}
Through FireBug, it looks like it is calling the open function of the ajaxRequest Object, but the PHP doesn't run! Is this something to do with the fact that it's calling it on the unload of the page?
Also, I've found an event called onbeforeunload, but I can't figure out how to get it working, if it still is available.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
“onbeforeunload”并不适用于所有浏览器。就像 chacha102 所说,您需要确保 PHP 脚本不会在请求终止时停止 -
ignore_user_abort()
是确保这一点的好方法。此外,您可能想尝试一些更简单的方法。您可能需要做的就是将图像注入页面以引发请求。
"onbeforeunload" isn't going to work in every browser. like chacha102 says, you need to make sure the PHP script isn't stopping the second the request is terminated -
ignore_user_abort()
is a good way to make sure of this.additionally, you might want to try something simpler. injecting an image into the page to spark the request might be all you need to do.
您需要确保尽快将
ignore_user_abort()
设置为 true。如果有默认设置就更好了。You need to make sure the
ignore_user_abort()
is set to true as soon as possible. If there is a default setting for it, that would be better.