在用戶端同步顯示伺服器時間解決辦法:
1.用ajax非同步提交取得時間,然後局部重新整理頁面。
2.取得伺服器時間,在本地(用戶端)實現時間累加。
第一種方法顯然加大了伺服器的負載量,但是時間準確。(中間網速另算)
第二中每次只取得一次時間,節約伺服器開銷。
這次我採用第二種方法實現此功能,希望對學習者有所協助。
首先在用戶端得到伺服器時間代碼如下:
<%
Date date = new Date();
%>
得到時間後用js函數進行累加
<script language="javascript">
var hours, minutes, seconds, xfile;
var intHours, intMinutes, intSeconds;
var today= new Date();
today.setTime(<%=date.getTime()%>); //把伺服器時間賦給JS函數
function time_callback(){
intHours = today.getHours();
intMinutes = today.getMinutes();
intSeconds = today.getSeconds();
if (intHours == 0) {
hours = "12 : ";
xfile = "午夜 ";
} else if (intHours < 12) {
hours = intHours+" : ";
xfile = "上午 ";
} else if (intHours == 12) {
hours = "12 : ";
xfile = "正午 ";
} else {
intHours = intHours - 12
hours = intHours + " : ";
xfile = "下午 ";
}
if (intMinutes < 10) {
minutes = "0"+intMinutes+" : ";
} else {
minutes = intMinutes+" : ";
}
if (intSeconds < 10) {
seconds = "0"+intSeconds+" ";
} else {
seconds = intSeconds+" ";
}
timeString = xfile+hours+minutes+seconds;
document.getElementById("time_view").innerHTML = " " + timeString;
today.setTime(today.getTime() + 1000);
}
setInterval("time_callback()",1000); //每1000毫秒回調此函數
</script>