你的位置:首页 > ASP.net教程

[ASP.net教程]页面时间自动更新


1、通过JavaScript获取本机的时间,自动更新

<script>
function displayTime() {
var date = new Date(); //日期对象
var now = "";
now = date.getFullYear() + "年";
now = now + (date.getMonth() + 1) + "月";
now = now + date.getDate() + "日";
now = now + date.getHours() + "时";
now = now + date.getMinutes() + "分";
now = now + date.getSeconds() + "秒";
document.getElementById("getToday").innerHTML = now;
setTimeout("displayTime()", 1000);
}
window.onload = displayTime;
</script>

<div id="getToday">
</div>

实用小技巧:通过JavaScript可以自动更新显示在网页底部版权处的年份

<script type="text/javascript">
copyright=new Date();//取得当前的日期
update=copyright.getFullYear();//取得当前的年份
document.write("Copyright &copy; 2015-"+ update + " All rights reserved.");
</script>

2、通过AJAX获取服务端的时间,在页面上自动更新

<script type="text/javascript" src="Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(function () {
setInterval(function () {
$.get("GetTime.aspx?timestamp="+new Date().getTime(),function (data) {
$("#time").html(data);
});
}, 1000);
})
</script>

<div id="time">
</div>

GetTime.aspx后台代码:

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{

Response.Write(DateTime.Now.ToString());
}
}

如果仅仅显示时间,用第1种方法,即通过JavaScript获取本机的时间,自动更新。