一个网页倒计时的实现

        最近要作一个网站上的活动倒计时的功能。在网上搜了一下,网上关于js倒计时的代码却是很多,可是正正能够应用到生产环境的则是少之又少。html

         好比我用到的这个就是这样的:ajax

var endDate=new Date(2014,7,25,23,59,59);
var begin = new Date();
var intDiff=Math.round((endDate.getTime()-begin)/1000);//初始日期
	
	function timer(intDiff){
		window.setInterval(function(){
		var day=0,
			hour=0,
			minute=0,
			second=0;//时间默认值		
		if(intDiff > 0){
			day = Math.floor(intDiff / (60 * 60 * 24));
			hour = Math.floor(intDiff / (60 * 60)) - (day * 24);
			minute = Math.floor(intDiff / 60) - (day * 24 * 60) - (hour * 60);
			second = Math.floor(intDiff) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
		}
		if(day==0&&hour==0&&minute==0&&second<=0){
			$("#timeshow").html("活动结束。");
		}
		if (minute <= 9) minute = '0' + minute;
		if (second <= 9) second = '0' + second;
		$('#day_show').html(day+'天');
		$('#hour_show').html(hour+'小时');
		$('#minute_show').html(minute+'分');
		$('#second_show').html(second+'秒');
		intDiff--;
		
		}, 1000);
	} 
	$(function(){
		timer(intDiff);
	});

看到了没,因为js是运行在客户端的,没法拿到服务器的时间,因此会致使“一千个读者眼里又一千个哈姆雷特”,这样是不对的,因此要得到服务器的时间。服务器

第一想到的是用ajax请求得到服务器的时间,可是会有问题,ajax是异步请求,js执行到那一段的时候ajax尚未执行完成,因此会出现取不到值得状况。因此否决了这样的作法。异步

解决方法是:网站

  <input type="hidden" id="serverTime" value="<%= request.getAttribute("time")%>"/>

在请求到这个页面以前,把时间放到atrribute里面,在页面拿到这个值,放到一个隐藏域里面。注意:定时器的代码要放到取值操做的后米阿尼,不然会出现隐藏域时空的状况。code


Get!
server

相关文章
相关标签/搜索