你的脚本所做的是在inc/clock.php上轮询服务器上的脚本,并用脚本的输出(大致)每秒替换#clock_time元素的内容。 这应该工作,只要你有id为clock_element一个元素,在脚本yoursite.tld/INC/clock.php
不过,我不同意不断地轮询服务器为它的当前时间。只需将一次同步到Web服务器就足够了。除了一些细微的差异之外,这应该能够让你的时钟同步好一段时间。如果你的web应用运行了几个小时或几天,你应该定期重新同步你的时钟(一天或一周应该做一次)。
使用Date对象跟踪客户端上的servertime。只需从clock.php的输出(作为先决条件的有效日期输出)创建一个Date对象,并根据从您的时钟与远程服务器同步时的时间增量定期更新您的clock_element(如每秒)。
这里是一些粗糙的代码,而不是测试,propably一些语法错误,但短暂地显示你应该做的:
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);
失踪几架...但水手不起作用..根本不显示时间。 – arturs 2010-10-24 14:28:45
那么你知道你的服务器实际返回什么吗?您可以使用Firebug(Firefox)或IE8调试器来检查XHR的响应。 – Pointy 2010-10-24 14:30:01
没有活动....... – arturs 2010-10-24 14:59:27