很多人习惯用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>