2013-01-25 63 views
0

我使用onbeforeunload通过Ajax请求重置变量。但它只执行一次。例如,如果我访问该页面(登录后)并关闭该窗口,则会执行该功能,但如果我重复该操作(将地址放入浏览器并完成登录并关闭窗口),则不会执行该功能。onbeforeunload仅执行一次

window.onbeforeunload = function (e) { 
    //Ajax request to reset variable in database 
    resetDemoValueWithAjax(); 
}; 

//Ajax request to reset variable in database and exit 
function resetDemoValueWithAjax(){ 
    $.ajax({ 
     async:true, 
     type: "POST", 
     dataType: "json", 
     url:"http://localhost/site/index.php/welcome/resetDemoValue", 
     data: {name: "demo"}, 
     success:function(){ 
      document.location.href='http://localhost/site/index.php/auth/logout'; 
     }, 
     error: function(){ 
      document.location.href='http://localhost/site/index.php/auth/logout'; 
     } 
    });  
} 

document.location.href='http://localhost/site/index.php/auth/logout';仅在另一时刻使用:当用户注销时。不在这里

回答

1

您有race condition。异步Ajax请求与浏览器尝试从页面导航(这首先导致beforeunload)之间的比赛。离开的导航可能总会赢,所以浏览器在Ajax回调完成之前离开页面。

如果您使得Ajax请求与async:false同步,则不会发生此比赛,因为在解决Ajax请求之前JavaScript线程会阻塞。请注意,这会导致潜在的恼人的用户体验(即,用户尝试关闭页面,但必须等待Ajax请求在标签关闭之前解析)。

+0

清晰简洁。谢谢。 – vicenrele