簡體   English   中英

如何使用ajax請求更改setTimeout()計數器?

[英]How to change the setTimeout() counter using an ajax request?

我寫了一個小的jQuery代碼,如果頁面在1800秒內沒有刷新,它將顯示一個對話框。 在會話自動結束之前,該對話框具有倒計時。 如果用戶單擊“是,繼續工作”,則計數器重置,對話框消失。 否則,用戶將被轉移到注銷頁面。

我這里遇到的問題是當用戶打開新瀏覽器的標簽並繼續使用新標簽時。 然后,舊選項卡將“在1800秒后無刷新”變為空閑狀態,因此它們會松開所有會話並退出。

我創建了一個PHP頁面,該頁面將通過使用$_SESSION信息檢查數據庫中的時間來返回剩余的秒數。 但是我不確定如何打開對話框時重置計數器。

我不確定如何修改代碼以檢查顯示對話框之前剩余的實際秒數。

這是我的代碼

<!-- 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>

在您的腳本php中,您只需要返回剩余的秒數
您的JavaScript需要以ajax請求開始到php頁面。

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

正如您所說,您需要檢查對話框打開之前的時間。 頁面加載后,您可以假設整個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() {...})現在包裝了所有內容。 這樣避免了使用全局名稱空間的需要。

新功能getSessionTimeRemaining()及其服務器端對應的getSessionTimeScript對於允許多個選項卡響應會話超時至關重要。

兩個腳本keepAliveScriptgetSessionTimeScript (可以是具有不同查詢字符串的同一腳本)都必須返回時間t (以秒為單位)。 假定t為字符串,並使用parseInt()將其轉換為Number。 您可能需要返回比實際會話剩余時間稍短的時間,從而允許短暫的“寬限期”。 您不需要的是讓用戶希望會話期滿后仍保持活動狀態。

函數startTimeoutCounter(t)現在接受一個以秒為單位的時間,因此它可以處理剩余的任何時間,它不一定是完整的1800秒,具體取決於調用是來自(異步地)來自keepAlive()還是getSessionTimeRemaining()

新的功能keepAlive()允許整潔的“按鈕”定義。

全部完全未經測試。 您可能仍然需要進行修改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM