据我所知,我无法通过脚本中的settimeout()在IE中获得动态服务器时间..我找到了这个例子:
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冲突(显示selectmenu错误)。我添加了脚本没有冲突代码,但它没用..必须删除prototype.js
答案 0 :(得分:3)
您的脚本所做的是在inc / clock.php上轮询服务器上的脚本,并用脚本(大致)每秒的输出替换#clock_time元素的内容。 如果您有一个id为clock_element的元素和一个位于yoursite.tld / inc / clock.php
的脚本,这应该可行。但是,我不同意不断轮询服务器的当前时间。只需将时间同步到您的网络服务器就足够了。除了一些微小的差异,这应该让你的时钟足够好地同步一段时间。如果您的网络应用程序运行超过几个小时或几天,您应该定期重新同步您的时钟(每天或每周一次)。
使用Date对象跟踪客户端上的servertime。只需从clock.php的输出(作为先决条件的有效日期输出)创建一个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 );
这将设置要写入#clock_element的时钟,使用从yourdomain.tld / inc / clock.php返回的值,每小时重新同步时钟并每秒更新时钟的本地表示。
哦,如果那个定期重新同步确实会在时钟中出现“跳跃”,你可以考虑简单地给用户反馈,他的时钟已经更新,例如像这样
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);
答案 1 :(得分:0)
因为你正在使用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请求,因为在当前的更新成功之前它不会设置新的更新。