0

在这篇文章中,我发布了一个问题,其中我正在使用 java 脚本和 PHP 代码,并使用 PHP 的时间函数发回时间戳。让代码,

<?php
session_start();
echo time();
?>

<html>
<head>
    <title>my app</title>
    <script type="text/javascript" src="jquery-2.0.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $(this).mousemove(function(){
                var time_=new Date();

                var time=<?php echo time();?>;
                alert(time);
                $.post('loggout.php',{input: time});
            });
        });

    </script>
</head>
<body>
    <h2>we are on the main_session</h2>
</body>
</html>

现在的问题是,当我移动鼠标时,mousemove 事件开始起作用并显示 var time 的值。但每次它显示相同的值。该值仅在我重新加载页面时更改。所以请让我知道它背后的原因以及如何使这个动态

4

3 回答 3

0

将此javascript代码放在您的php文件中的任何位置。

<script type="text/javascript">    
    var currenttime = '<?php echo date("F d, Y H:i:s"); ?>' //PHP method of getting server date    
    var montharray=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
    var serverdate=new Date(currenttime)

function padlength(what){
   var output=(what.toString().length==1)? "0"+what : what
   return output
}

function displaytime(){
   serverdate.setSeconds(serverdate.getSeconds()+1)
   var datestring=montharray[serverdate.getMonth()]+" "+padlength(serverdate.getDate())+", "+serverdate.getFullYear()
   var timestring=padlength(serverdate.getHours())+":"+padlength(serverdate.getMinutes())+":"+padlength(serverdate.getSeconds())
   document.getElementById("servertime").innerHTML=timestring
}
window.onload=function(){
setInterval("displaytime()", 1000);
}
</script>

在要显示当前时间的地方添加 span 或 div。无需重新加载页面。

 <span id="servertime"></span>
于 2013-08-01T11:15:21.093 回答
0

This is because the PHP is only run once - when the page loads. So the Javascript time variable gets filled with the time returned by PHP and then never changes.

If you're happy to get the client-side time, just use this:

 var time = time.getTime();

Instead of var time=<?php echo time();?>;

Otherwise, you can use AJAX to send a query that'll run some PHP, return the time, and put it into the variable.

For example, you could try something like this:

$.get('getTime.php', function(data) {
    time = data;
});

And in getTime.php, just echo the time.

于 2013-08-01T10:34:24.940 回答
0

This is because PHP is back-end programing language and once your page loaded timestamp written to code and can't be dynamic. But you can send JS timestamp:

var time = Math.round(+new Date() / 1000);

( + will convert date Object to integer )

or

var time = Math.round(new Date().getTime() / 1000);

division by 1000 needed because JS use milliseconds.

See Date reference at MDN.

于 2013-08-01T10:34:54.520 回答