如何在用户关闭浏览器/选项卡之前激活功能?

use*_*335 2 javascript ajax jquery

如何在用户关闭浏览器/选项卡之前激活功能?

下面是我的ajax请求

<script language="JavaScript" type="text/javascript">
 function srh_ajaxfunction_cny(id)
    {var xmlhttp;
    try{xmlhttp=new XMLHttpRequest();}
    catch (e){try{xmlhttp=new ActiveXObject("msxml2.xmlhttp");}
    catch (e){try{xmlhttp=new ActiveXObject("microsoft.xmlhttp");}
    catch (e){alert("Your browser does not support ajax!");      
    return false;}}}
    xmlhttp.onreadystatechange=function(){
    if(xmlhttp.readyState==4){
        alert('done')
    }}  

        xmlhttp.open("get",url_path,true);
        xmlhttp.send(null); 
    }
</script>
Run Code Online (Sandbox Code Playgroud)

WTK*_*WTK 8

使用beforeunload事件.通常,如果该处理程序中存在异步操作,浏览器将不会等待它们完成并继续页面卸载(在它到达您的服务器之前有效地中断您的ajax调用).

在浏览器卸载页面之前,有一些(hackish)技巧可以确保你的ajax通过.其中一个(例如用于跟踪您在网页上的行为的服务)正在执行循环,如下所示:

window.addEventListener('beforeunload', function() {
    // number of miliseconds to hold before unloading page
    var x = 200;
    var a = (new Date()).getTime() + x;

    // -----------
    // your ajax call goes here
    // -----------

    // browser will hold with unloading your page for X miliseconds, letting
    // your ajax call to finish
    while ((new Date()).getTime() < a) {}
}, false)
Run Code Online (Sandbox Code Playgroud)