你的腳本所做的是在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