【问题标题】:How to display timestamp on a website and terminate a session after a particular time?如何在网站上显示时间戳并在特定时间后终止会话?
【发布时间】:2018-08-17 08:29:41
【问题描述】:

所以我有这段代码显示当前时间戳(IST)

<?php echo date("D M d, Y "); ?> </b>
    <body onload="digiclock()">
    <div id="txt"></div>
    <script>
   function digiclock()
   {
     var d=new Date();
     var h=d.getHours();
     var m=d.getMinutes();
     var s=d.getSeconds();
     if(s==60)
     {
       s=0;
       m+=1;
     }
     if(m==60)
     {
       m=0;
       h+=1;
     }
     if(h==12)
     {
       h=0;
     }
     var t=h>=12?'PM':'AM';
     document.getElementById('txt').innerHTML=h+":"+m+":"+s+" "+t;
     var t=setTimeout(digiclock,500);
   }

如何压缩此代码以及如何使用它来计算终止会话的时间限制。例如,一个人正在玩测验,测验应在 5 分钟后终止,并根据尝试的问题生成分数。

【问题讨论】:

    标签: javascript php html web


    【解决方案1】:

    这里是如何使用@rckrd 的 js 代码 sn-p 与 AJAX 调用的 PHP 脚本的示例。 这个例子很基础,只是为了演示实现逻辑。

    你不能在这里寻找现场演示http://demo1.rrsoft.cz/

    在此处下载代码http://demo1.rrsoft.cz/test.zip

    带有 HTML 代码的 index.php:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    </head>
    <body>
    
    <button onclick="startQuiz()">Start timer</button>
    
    <div id="messages"></div>
    <div id="timerView"></div>
    <div id="quiz_body"></div>
    
    <script src="ajax.js"></script>
    </body>
    </html>
    

    带有所需功能的 ajax.js(我使用了@rckrd sn-p,因为这是一个很好的例子,如何将它与 PHP 一起使用)

    // This function has call php script with quiz answer...
    
    var doAnswer = function(number){
        var response_value = $('[name="qr'+number+'"]').val();
        var response_message = '"Quiz #' + number + ' has successfuly saved';
    
        $('[name="qr'+number+'"]').prop( "disabled", true );
        $.ajax({
                url: '/answer.php',
                type: 'POST',
                async: true,
                data: {
                    quiz: number,
                    value: response_value
                },
                success:function(response){
                    if(response === 'OK'){
                        $('#messages').html(response_message);
                    }
                },
                error: function(xhr, type, exception) {
                    var _msg = "Service through error: ("+xhr.status+") " + exception.toString();
                    var _err = $('#messages');
                        _err.text(_msg).show();
                }
            });
    }
    
    // This function just call the php script to render all quiz questions...
    var startQuiz = function(){
        $.ajax({
                url: '/quiz.php',
                type: 'GET',
                async: true,
                data: {
                    started: true
                },
                success:function(response){
                    $('#quiz_body').html(response);
                    startTimer();
                },
                error: function(xhr, type, exception) {
                    var _msg = "Service through error: ("+xhr.status+") " + exception.toString();
                    var _err = $('#messages');
                        _err.text(_msg).show();
                }
            });
    }
    
    // Arange elements over time limit
    var gameOver = function(){
        $('#header').html('Game over');
        $('#list').hide();
    }
    
    // This function manage time limitation logic and is called when quiz has started...
    var startTimer = function (){
        var timeLeftInMillis = 1*60*1000;
        var startTime = new Date().getTime();
        var updateTimeInMillis = 25;
        var intervalId = setInterval(function(){
        var now = new Date().getTime();
        var diffInMills = now - startTime;
        startTime = new Date().getTime();
        timeLeftInMillis = timeLeftInMillis - diffInMills;
        var oneSecondInMillis = 1000;
        if(timeLeftInMillis < oneSecondInMillis){
            clearInterval(intervalId);
            gameOver();
            return;
        }
        var seconds = Math.floor((timeLeftInMillis / 1000) % 60) ;
        var minutes =  Math.floor((timeLeftInMillis / (1000*60)) % 60);
        document.getElementById("timerView").innerHTML = minutes + ' min, ' +seconds+' sec remaining';
        },updateTimeInMillis);
    };
    

    AJAX调用的quiz.php:

    <?php
    
    // very easy list of quizes...
    $quiz_template = '
        <h1 id="header">Quiz started!</h1>
        <ul id="list">
            <li>
                Quiz 1 text
                <input type="text" name="qr1" size="5"/>
                <button id="bt1" onclick="doAnswer(1)">Send answer</button>
            </li>
            <li>
                Quiz 2 text
                <input type="text" name="qr2" size="5"/>
                <button id="bt2" onclick="doAnswer(2)">Send answer</button>
            </li>
            <li>
                Quiz 3 text
                <input type="text" name="qr3" size="5"/>
                <button id="bt3" onclick="doAnswer(3)">Send answer</button>
            </li>
            <li>
                Quiz 4 text
                <input type="text" name="qr4" size="5"/>
                <button id="bt4" onclick="doAnswer(4)">Send answer</button>
            </li>
            <li>
                Quiz 5 text
                <input type="text" name="qr5" size="5"/>
                <button id="bt5" onclick="doAnswer(5)">Send answer</button>
            </li>
    
        </ul>
    ';
    
    // ... and return it
    if((bool) $_GET['started'] === true){
        die($quiz_template);
    }
    

    最后是 answer.php

    <?php
    
    if($_POST){
        // grab all needed posted variables... THIS IS JUST FOR DEMO, BECAUSE IS UNSECURED
        $quizNumber = $_POST['quiz'];
        $quirAnswer = $_POST['value'];
    
        // do quiz PHP logic here, save answer to DB etc...
    
        // when php script runs without errors, just return OK
        $error = false;
    
        if($error === false){
            die('OK');
        }else{
            die($someErrorMessage);
        }
    }
    

    【讨论】:

    • 很有帮助。谢谢:)
    【解决方案2】:

    var gameOver = function(){
      document.getElementById("timerView").innerHTML = 'Game over';
    }
    var startTimer = function (){
      var timeLeftInMillis = 5*60*1000;
      var startTime = new Date().getTime();
      var updateTimeInMillis = 25;
      var intervalId = setInterval(function(){
        var now = new Date().getTime();
        var diffInMills = now - startTime; 
        startTime = new Date().getTime();
        timeLeftInMillis = timeLeftInMillis - diffInMills;
        var oneSecondInMillis = 1000; 
        if(timeLeftInMillis < oneSecondInMillis){
          clearInterval(intervalId);
          gameOver();
          return;
        }
        var seconds = Math.floor((timeLeftInMillis / 1000) % 60) ;
        var minutes =  Math.floor((timeLeftInMillis / (1000*60)) % 60);
        document.getElementById("timerView").innerHTML = minutes + ' min, ' +seconds+' sec remaining';
      },updateTimeInMillis);
    };
    <button onclick="startTimer()">Start timer</button>
    <div id="timerView"></div>

    【讨论】:

      【解决方案3】:

      如果您愿意使用第三方库,请查看 EasyTimer.js 插件,这将解决问题。 https://albert-gonzalez.github.io/easytimer.js/

      countdownjs:http://countdownjs.org/demo.html

      【讨论】:

        【解决方案4】:

        这在 php 中是不可能的,最好的方法是使用 JavaScript/Ajax...

        【讨论】:

        • 当然,请看我的回答,下载代码链接等。希望对您有所帮助...
        猜你喜欢
        • 1970-01-01
        • 2014-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-07
        • 1970-01-01
        • 2018-10-12
        • 1970-01-01
        相关资源
        最近更新 更多