据我所知,我无法在IE中通过脚本中的settimeout()获得动态服务器时间。我找到了这个例子:
function timeExam(){
$.ajax({
url : "inc/clock.php",
success : function (data) {
$("#clock_time").html(data);
}
});
var func = function()
{
timeExam();
}
setTimeout(func, 1000);
}
<body onload="timeExam();">
bla bla bla
</body>
也许有可能让它工作?
如果没有,你能给我推荐一个可以在所有浏览器上工作的动态时钟吗?!我尝试用prototype.js计时,但它与IE8中的jquery UI冲突(不能正确显示选择菜单)。我补充说,脚本没有冲突的代码,但它是无用的。had必须删除prototype.js
发布于 2010-10-24 22:09:06
您的脚本所做的就是轮询位于inc/clock.php的服务器上的脚本,并(大致)每秒用脚本的输出替换#clock_time元素的内容。如果您在您的site.tld/inc/clock.php中有一个id为clock_element的元素和一个脚本,那么这应该是可行的
但是,我不同意不断轮询服务器的当前时间。只需将时间同步到您的your服务器一次就足够了。除了一些细微的差异之外,这应该会让你的时钟在一段时间内保持良好的同步。如果你的webapp运行超过几个小时或几天,你应该定期重新同步你的时钟(一天一次或一周一次)。
使用Date对象来跟踪客户端上的服务器时间。只需从clock.php的输出创建一个Date对象(一个有效的date输出作为先决条件),并根据您与远程服务器同步时钟时的时间增量定期更新您的clock_element (如每秒)。
这里有一些粗略的代码,没有经过测试,可能有一些语法错误,但简要说明了您应该做什么:
function setupServerClock( clock_element, remote_time_url, remote_update_interval, local_update_interval ) {
var w = window;
// client time on resync
var ct = new Date();
// server time on resync
var st = new Date();
// setup resync
w.setInterval( function() {
jQuery.ajax( {
url: remote_time_url,
success: function (data) {
ct = new Date();
st = new Date(data);
}
});
}, remote_update_interval);
// setup local clock display
w.setInterval( function() {
// the time passed on our local machine since the last resync
var delta = new Date() - ct;
// we assume the same time passed at the server
// (yeah, I know, spacetime might not be the same at the servers
// place and off the shelve clocks are pretty inaccurate)
var clock = st - 0 + delta; // - 0 to convert to microsecond timestamp
jQuery(clock_element).html(new Date(clock));
}, local_update_interval);
}
用下面这样的方式调用它:
setupServerClock( jQuery('#clock_element'), 'inc/clock.php', 1000 * 60 * 60, 1000 );
这将使用从您的domain.tld/inc/clock.php返回的值将时钟设置为写入#clock_element,每小时重新同步时钟,每秒更新时钟的本地表示。
哦,如果周期性的重新同步确实在时钟中产生了“跳跃”,你可以考虑简单地给用户反馈,他的时钟已经更新了,例如这样
w.setInterval( function() {
jQuery(clock_element).html('resyncing clock...');
jQuery.ajax( {
url: remote_time_url,
success: function (data) {
ct = new Date();
st = new Date(data);
}
});
}, remote_update_interval);
发布于 2010-10-24 22:08:55
由于您使用的是jQuery:
$(function() {
var updateSeconds = 60;
function updateClock() {
$.ajax({
url : "inc/clock.php",
success : function (data) {
$("#clock_time").html(data);
setTimeout(updateClock, updateSeconds * 1000);
}
});
}
setTimeout(updateClock, updateSeconds * 1000);
});
您可以随意更改"updateSeconds“。
我用setTimeout
而不是setInterval
做这件事,因为它更安全一点。如果服务器出现问题,这个服务器不会一次又一次地堆积注定要失败的HTTP请求,因为在当前更新成功之前,它不会设置新的更新。
https://stackoverflow.com/questions/4008512
复制相似问题