admin管理员组文章数量:1323723
I have a situation where I want the server time to be displayed on a web page. At present I keep it simple and just do this
<?php
$CTIME=date ("g:i a");
?>
This works great- except I would prefer it if it updated by itself without the need to refresh the page. I was thinking perhaps there is a way I can set the javascript time function with the time from a php script- but I've got no idea as to how I could go about doing this.
Perhaps I'm thinking about this wrong... maybe there is another solutions I'm not thinking of, Any ideas ??
I have a situation where I want the server time to be displayed on a web page. At present I keep it simple and just do this
<?php
$CTIME=date ("g:i a");
?>
This works great- except I would prefer it if it updated by itself without the need to refresh the page. I was thinking perhaps there is a way I can set the javascript time function with the time from a php script- but I've got no idea as to how I could go about doing this.
Perhaps I'm thinking about this wrong... maybe there is another solutions I'm not thinking of, Any ideas ??
Share Improve this question asked Jun 8, 2011 at 22:07 AlexAlex 411 silver badge2 bronze badges4 Answers
Reset to default 3Here is a jQuery plugin for displaying a clock:
http://plugins.jquery./project/jqClock
Just initialize it using the time ing back from the server. It automatically updates every second on the client side.
Try this:
<javascript>
var ctime = '<?php echo date ("g:i a"); ?>';
</javascript>
Then let a timer increase the value on the javascript side. It's not very precise, but if I saw that right you need minutes only, not seconds, so precision is probably not an issue.
Use your base-time to calculate the current time on the fly (without using any additional and potentially slow/expensive request; it does not even require jQuery):
var getServerTime = (function () {
var baseTime = <?php echo time() * 1000; /* convert to milliseconds */ ?>,
startTime = new Date().getTime();
return function () {
return baseTime + (new Date().getTime() - startTime);
};
}());
This function returns the current time (in milliseconds) based on the server-side time. You can update your site an a regular interval and use this function to determine the current server-side time like this:
// update the site every minute
setInterval(function () {
var currentServerTime = getServerTime();
// update everything (format date or something)
}, 60 * 1000);
I believe you can easily find some javascript code over the internet which shows a running clock on your site. On load of the page have PHP set the initial start time for this javascript snippet and i believe you are good to go.
本文标签: Set Javascript time with php server timeStack Overflow
版权声明:本文标题:Set Javascript time with php server time? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742123746a2421843.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论