標籤:io 2014 re 問題 c cti
最近要做一個網站上的活動倒計時的功能。在網上搜了一下,網上關於js倒計時的代碼倒是不少,但是正正可以應用到生產環境的則是少之又少。
比如我用到的這個就是這樣的:
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裡面,在頁面拿到這個值,放到一個隱藏欄位裡面。注意:定時器的代碼要放到取值操作的後米阿尼,否則會出現隱藏欄位時空的情況。
Get!