2013-01-25 4 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과 동기화하면 JavaScript 스레드가 Ajax 요청이 해결 될 때까지 차단되므로이 레이스는 발생하지 않습니다. 이로 인해 잠재적으로 성가신 사용자 환경이 발생합니다 (즉, 사용자가 페이지를 닫으려고 시도하지만 탭이 닫히기 전에 Ajax 요청이 해결 될 때까지 기다려야 함).

+0

명확하고 간결합니다. 감사. – vicenrele