[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后四舍五入

相关文章
相关标签/搜索