開發時常會遇到客戶要求「頁面不要被快取」的需求,以確保每次都能取得最新的資料。以下整理 HTML、ASP、PHP 三種常見的實作方式。
只要把下列三行 meta 標籤放在 <head> 之間即可:
<head>
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Expires" content="0">
</head>
Response.Buffer = True
Response.ExpiresAbsolute = Now() - 1
Response.Expires = 0
Response.CacheControl = "no-cache"
Response.AddHeader "Pragma", "No-Cache"
<?php
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');
?>
此外還有一種更簡單的做法,就是在做 AJAX 請求時於網址後方附加一組隨機參數(例如 ?t=隨機數字),讓每次請求的網址都不同,瀏覽器便不會命中舊的快取。