1. 程式人生 > >java每秒更新頁面時間,用jquery ajax方法呼叫

java每秒更新頁面時間,用jquery ajax方法呼叫

很多人習慣用javaScript來獲取系統的時間 更新網站頁面上得時間,此方法也比較實用方便,但是對於往往需要安全度很高或者用來製作定時測驗系統等一些需要通過準確計時的工具或者網站時,用javaScript的方式很容易在使用者禁用遊覽器javaScript指令碼時而無效。

因此自己寫了一段比較簡單的,通過ajax的方式來更新頁面時間,當然此方法需要與伺服器互動。從而多多少少的會影響遊覽的速度,不過在載入少的網頁 還是感覺不出來的。

JavaAction 程式碼:

private Date time;
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}

/***
* AJAX方法 更新時間
* @throws IOException
*/
public void ajaxTime() throws IOException{
HttpServletResponse response = ServletActionContext.getResponse();  
response.setContentType( "text/html;charset=utf-8 ");
PrintWriter out;
out = response.getWriter();
time = new Date();
out.print(time);   //輸出更新後的時間
}

jquery ajax:

<script>
function updateTime(){
$.get("ajaxTime.htm",function(result){   //jquery $.get方法提交返回更新後的時間
$("#dateTime").text(result)      //重新整理到dateTime div上
})
}

$(function(){
setInterval('updateTime()', 1000);  //定時每秒啟用updateTime更新時間資料
    });
</script>

測試div:

<div id="dateTime" style="color:red">${time }</div>