Running a PHP through Ajax on Unload

我怕爱的太早我们不能终老 提交于 2019-12-02 05:20:31

问题


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.


回答1:


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.




回答2:


"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.

function onunload() { 
  var i = document.createElement("img");
  i.src = "ajax/cancelMatch.php?" + Math.random();
  document.appendChild(i);
  return;
}


来源:https://stackoverflow.com/questions/1297750/running-a-php-through-ajax-on-unload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!