在PHP代码中实现倒计时js倒计时

时间:2016-04-28 07:15:59

标签: javascript php jquery countdowntimer throttling

我完成了用于限制登录的PHP代码,但是现在我想使用简单的js或jquery代码来从php获取限制计数停机时间并进行实时倒计时。

我应该将js脚本放在php文件中吗?还是html文件?如果是这样,我应该如何编辑我的代码?

到目前为止,我已将span id计时器放入php,现在显示计时器但是我再也没有得到php live timer

我的PHP代码:

<?php
include('database.php');
function get_multiple_rows($getfailed) {
    $rows = array();
    while($row = $getfailed->fetch_assoc()) {
        $rows[] = $row;
    }
    return $rows;
}
$throttle = array(1 => 1, 5 => 2, 10 => 30);
$getfailedq = "SELECT MAX(attempted) AS attempted FROM failed_logins";    
if ($getfailed = $mySQL->query($getfailedq)) {
    $rows = get_multiple_rows($getfailed);
    $getfailed->free();
    $latest_attempt = (int) date('U', strtotime($rows[0]['attempted'])); 
    $getfailedq = "SELECT COUNT(1) AS failed FROM failed_logins WHERE attempted > DATE_SUB(NOW(), INTERVAL 15 minute)";   
    if ($getfailed = $mySQL->query($getfailedq)) {
        $rows = get_multiple_rows($getfailed);
        $getfailed->free();
        $failed_attempts = (int) $rows[0]['failed'];
        krsort($throttle);
        foreach ($throttle as $attempts => $delay) {
            if ($failed_attempts > $attempts) {
                $remaining_delay = (time() - $latest_attempt) - $delay;
                if ($remaining_delay < 0) {echo '<span id="timer">' . abs($remaining_delay) . '</span>';}                
                break;
            }
        }        
    }
}
?>

我的js:

<script>
var count=30;
var counter=setInterval(timer, 1000); //1000 will  run it every 1 second
function timer(){
    count=count-1;
    if (count <= 0){
        clearInterval(counter);
        return;
    }
    document.getElementById("timer").innerHTML=count + " secs"; // watch for spelling
}
</script>

1 个答案:

答案 0 :(得分:1)

您可以通过PHP变量liek初始化您的JS变量:

var counter = <?php echo $counter; ?>;  

在JS中创建你的计数器。

编辑#1:
初始化变量后,您需要将其计算下来。

var counter = <?php echo $counter; ?>;  
setInterval(function () {
    console.log(counter);
    counter--;
}, 1000 /*ms*/ );