2014-10-06 2 views
0

페이지가 1800 초 동안 새로 고쳐지지 않으면 대화 상자를 표시하는 작은 jQuery 코드를 작성했습니다. 대화 상자에는 세션이 자동으로 끝나기 전에 카운트 다운이 있습니다. 사용자가 "예, 계속 작업"을 클릭하면 카운터가 재설정되고 대화 상자가 사라집니다. 그렇지 않으면 사용자가 로그 아웃 페이지로 이동됩니다.ajax 요청을 사용하여 setTimeout() 카운터를 변경하는 방법은 무엇입니까?

사용자가 새 브라우저 탭을 열고 새 탭에서 계속 작업 할 때의 문제입니다. 그런 다음 이전 탭은 "새로 고침이없는 1800 초 후"유휴 상태가되어 세션을 모두 풀어 로그 아웃합니다.

$_SESSION 정보를 사용하여 데이터베이스에서 시간을 확인하여 남은 시간을 반환하는 PHP 페이지를 만들었습니다. 그러나 대화 상자가 열릴 때의 카운터를 어떻게 재설정 할 수 있는지 잘 모르겠습니다.

대화 상자가 표시되기 전에 남은 실제 시간을 확인하기 위해 코드를 어떻게 수정할 수 있는지 잘 모르겠습니다.

여기에 유 secondes의 수는
자바 스크립트는 PHP 페이지에 아약스 요청을 시작할 필요가 왼쪽 반환해야 내 코드를 통해 UR 스크립트 PHP에서

<!-- This script will alert a user before forcing to logout --> 
<script type="text/javascript"> 
    var timer; 
    var closeDialogAfter = 180; //The default counter value 
    var idleTimeOutLimit = 1800 - closeDialogAfter; //Display the dialog after @idleTimeOutLimit seconds of idle time 
    var signOutScript = '/index.php?action=logout'; //logout url 
    var keepAliveScript = '/ajax/handler-keep-me-alive.php'; //php page to handle ajax request to keep the session alive 
    var dialogCountdown = '#dialog-countdown'; // the lable that is used to display the counter 
    var idleTimeout= '#idleTimeout'; //the div that is used for the dialog 

    $(function(){ 

     //start the idle time out counter 
     startTimeoutCounter(); 

     $(idleTimeout).dialog({ 
      resizable: false, 
      autoOpen: false, 
      width: 400, 
      open: function(){ 
       updateTimeoutCounter(); 
      }, 
      buttons: { 
       "Yes, Keep working": function(e) { 
        $.ajax({  
         url: keepAliveScript,  
         success: function(data) { 
          startTimeoutCounter(); 
          $(idleTimeout).dialog("close"); 
         } 
        }); 
       }, 
       "No, End Session": function(e){ 
        forceLogOut(); 
        $(this).dialog('close');     
       } 
      } 
     }); 
    }); 


    function startTimeoutCounter(){ 
     timer = closeDialogAfter; 
     $(dialogCountdown).text(timer); 

     setTimeout(function(){ 
      $(idleTimeout).dialog("open"); 
     }, idleTimeOutLimit * 1000); 
    } 

    function updateTimeoutCounter(){ 

     if( $(idleTimeout).dialog("isOpen")){ 

      setTimeout(function(){ 
       timer = timer -1; 
       $(dialogCountdown).text(timer); 
       (timer < 2) ? forceLogOut() : updateTimeoutCounter(); 
      }, 1000); 
     } else 
      $(dialogCountdown).text(closeDialogAfter) 
    } 

    function forceLogOut(){ 
     window.location = signOutScript; 
    } 

</script> 
+1

localstorage를 사용하여 탭에서 남은 시간을 설정해보십시오. – juvian

+0

@juvian 로컬 저장소는 어떻게 사용합니까? – Jaylen

+0

탭이란 무엇을 의미합니까? –

답변

0

입니다.

<script type="text/javascript"> 
    $.get("timeleft.php",function(data){ 
     var timer; 
     var closeDialogAfter = parseInt(data); //<-- what i changed 
     var idleTimeOutLimit = 1800 - closeDialogAfter; //Display the dialog after @idleTimeOutLimit seconds of idle time 
     var signOutScript = '/index.php?action=logout'; //logout url 
     var keepAliveScript = '/ajax/handler-keep-me-alive.php'; //php page to handle ajax request to keep the session alive 
     var dialogCountdown = '#dialog-countdown'; // the lable that is used to display the counter 
     var idleTimeout= '#idleTimeout'; //the div that is used for the dialog 

     $(function(){ 

      //start the idle time out counter 
      startTimeoutCounter(); 

      $(idleTimeout).dialog({ 
       resizable: false, 
       autoOpen: false, 
       width: 400, 
       open: function(){ 
        updateTimeoutCounter(); 
       }, 
       buttons: { 
        "Yes, Keep working": function(e) { 
         $.ajax({  
          url: keepAliveScript,  
          success: function(data) { 
           startTimeoutCounter(); 
           $(idleTimeout).dialog("close"); 
          } 
         }); 
        }, 
        "No, End Session": function(e){ 
         forceLogOut(); 
         $(this).dialog('close');     
        } 
       } 
      }); 
     }); 


     function startTimeoutCounter(){ 
      timer = closeDialogAfter; 
      $(dialogCountdown).text(timer); 

      setTimeout(function(){ 
       $(idleTimeout).dialog("open"); 
      }, idleTimeOutLimit * 1000); 
     } 

     function updateTimeoutCounter(){ 

      if( $(idleTimeout).dialog("isOpen")){ 

       setTimeout(function(){ 
        timer = timer -1; 
        $(dialogCountdown).text(timer); 
        (timer < 2) ? forceLogOut() : updateTimeoutCounter(); 
       }, 1000); 
      } else 
       $(dialogCountdown).text(closeDialogAfter) 
     } 

     function forceLogOut(){ 
      window.location = signOutScript; 
     } 
    }); 
</script> 
+0

이 코드는 어디에 두어야합니까? – Jaylen

+0

나는 코드를 편집했다. –

+0

페이지가로드 될 때만 코드가 현재 세션을 읽습니다. 하지만 필요한 것은 페이지가로드 될 때가 아니라 대화창이 열리기 전에 시간을 확인하는 것입니다. – Jaylen

0

대화가 열리기 전에 시간을 확인해야합니다. 페이지가로드되면 전체 1800 초를 가정 할 수 있습니다.

아마도 이런 식으로하고 싶을 것입니다 (아래의 코드 및 메모 참조).

<!-- This script will alert a user before forcing to logout --> 
<script type="text/javascript"> 
$(function() { 
    var timer; 
    var closeDialogAfter = 180; //The default counter value 
    var idleTimeOutLimit = <?php echo $sessionTimeoutValue ?>; //Time after which 
    var signOutScript = '/index.php?action=logout'; //logout url 
    var keepAliveScript = '/ajax/handler-keep-me-alive.php'; //php page to handle ajax request to keep the session alive 
    var getSessionTimeScript = '/ajax/get_session_time.php'; //php page to handle ajax request for the remaining session length 
    var $dialogCountdown = $('#dialog-countdown'); //the container used to display the counter 
    var $idleTimeout = $('#idleTimeout'); //the div that is used for the dialog 

    function startTimeoutCounter(t) { 
     t = Math.max(closeDialogAfter, parseInt(t, 10) || 0); 
     $idleTimeout.dialog("close"); 
     setTimeout(getSessionTimeRemaining, (t - closeDialogAfter) * 1000); 
    } 
    function updateTimeoutCounter() { 
     if($idleTimeout.dialog("isOpen")) { 
      setTimeout(function() { 
       timer = timer - 1; 
       $dialogCountdown.text(timer); 
       if(timer < 2) { 
        // Here, forceLogOut() can't be assumed because 
        // the session may have been kept alive from another tab. 
        // Therefore, call getSessionTimeRemaining(). 
        getSessionTimeRemaining(); 
       } else { 
        updateTimeoutCounter(); 
       } 
      }, 1000); 
     } else { 
      $dialogCountdown.text(closeDialogAfter); 
     } 
    } 
    function forceLogOut() { 
     $idleTimeout.dialog("close"); 
     window.location = signOutScript; 
    } 
    function getSessionTimeRemaining() { 
     $.get(getSessionTimeScript).then(function(t) { 
      t = parseInt(t, 10) || 0; 
      if(t <= 0) { 
       forceLogOut(); 
      } else if(t <= closeDialogAfter) { 
       timer = closeDialogAfter; 
       $dialogCountdown.text(timer); 
       $idleTimeout.dialog("open"); 
      } else { 
       startTimeoutCounter(t); 
      } 
     }, function(error) { 
      // Something went wrong, safest action is logout 
      // This will only happen under abnormal circumstances 
      console.error(error); 
      forceLogOut(); 
     }); 
    }; 
    function keepAlive() { 
     $.get(keepAliveScript).then(startTimeoutCounter); 
    } 

    $idleTimeout.dialog({ 
     resizable: false, 
     autoOpen: false, 
     width: 400, 
     open: updateTimeoutCounter, 
     buttons: { 
      "Yes, Keep working": keepAlive, 
      "No, End Session": forceLogOut 
     } 
    }); 
    // On page load, the session should have been reset by the script that serves this page, 
    // therefore no need to call keepAlive(), though that would do the same job. 
    startTimeoutCounter(idleTimeOutLimit); 
}); 
</script> 

주요 구조적 차이점은 $(function() {...})이 이제 모든 것을 포함한다는 것입니다. 이렇게하면 전역 이름 공간을 사용할 필요가 없습니다.

새로운 fuction getSessionTimeRemaining() 및 해당 서버 쪽 카운터 getSessionTimeScript은 둘 이상의 탭이 세션 시간 초과에 응답 할 수 있도록하는 핵심 요소입니다.

두 개의 스크립트 keepAliveScriptgetSessionTimeScript (다른 쿼리 문자열이있는 동일한 스크립트 일 수 있음)은 모두 초 단위로 시간을 반환해야합니다 (t). tparseInt()으로 Number로 변환되는 String으로 가정합니다. 남아있는 실제 세션 시간보다 약간 작은 시간을 되돌려 주어 짧은 "은혜 기간"을 허용 할 수 있습니다. 당신이 원하지 않는 것은 세션이 이미 만료되었을 때 세션을 유지하기를 희망한다는 것입니다. 그것은 반드시 호출 (비동기) keepAlive() 또는 getSessionTimeRemaining()에서 제공 여부에 따라 전체 1천8백초하지 않을 것이다, 여전히 어떤 시간에 작업 할 수 있도록

기능 startTimeoutCounter(t) 이제 초 단위로 시간을 받아들입니다.

새로운 기능 keepAlive()은 깔끔한 '버튼'정의를 허용합니다.

모두 완전히 테스트되지 않았습니다. 당신은 아마 그것으로 주위를 어지를 필요가있을 것이다.

관련 문제