[PHP|Smarty|Js]在URL中加入Unix時間戳防止web頁面緩存

[PHP|Smarty|Js]在URL中加入Unix時間戳防止web頁面緩存

通常web頁面每次請求的url地址都同樣,
很容易被瀏覽器本地或者網絡設備緩存,
用戶常常會抱怨爲什麼頁面刷新了不少次了都沒變化。javascript

爲了防止頁面被緩存,不管是GET或者POST方式,在url中加入隨機數是一種不錯的作法。php

瞄了下新浪微博的request:html

http://weibo.com/ajm/weiqun?action=aj_remindunread&_t=0&__rnd=1328578563666java

能夠看到在url的末尾有參數&__rnd=1328578563666
__rnd應該是random的意思吧- -
1328578563666應該是當前unix時間戳,單位毫秒web

這個參數每次請求是生成,值是當前的unix時間戳,這樣每次請求的url都不同,
頁面就不容易被瀏覽器或者網絡設備緩存了瀏覽器

提供幾種unix時間戳生成辦法,記錄下備忘緩存

1.php獲取unix時間戳網絡

在php中能夠使用time()函數來得到unix時間戳,單位爲秒dom

2.smarty獲取unix時間戳函數

在smarty模板引擎中,有一個叫{$smarty.now}的保留變量,能夠得到unix時間戳,單位爲秒

詳細用法:
{$smarty.now}
The current timestamp can be accessed with {$smarty.now}. The number reflects the number of seconds passed since the so-called Epoch (January 1, 1970) and can be passed directly to date_format modifier for display purposes.

Example 4-7. using {$smarty.now}

{* use the date_format modifier to show current date and time *}
{$smarty.now|date_format:」%Y-%m-%d %H:%M:%S」}

3.js (javascript)獲取unix時間戳

new Date().getTime()

得到unix時間戳,getTime()返回數值的單位是毫秒

若是要得到單位爲秒的時間戳,能夠進一步處理下 Math.round(new Date().getTime()/1000) 除1000後四捨五入

相關文章
相關標籤/搜索