2012-07-05 104 views
2

我需要浏览器缓存一个大的,大多数是静态的.php文件。我通过ajax打开它,并希望将其添加到当前页面。强制浏览器缓存一个.php文件

经过研究后,若发现this

$seconds_to_cache = 3600; 
$ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT"; 
header("Expires: $ts"); 
header("Pragma: cache"); 
header("Cache-Control: max-age=$seconds_to_cache"); 

这适用于IE浏览器,而不是Chrome和Firefox。

这里是请求

Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 
Accept-Encoding gzip, deflate 
Accept-Language de-de,de;q=0.8,en-us;q=0.5,en;q=0.3 
Cache-Control max-age=0 
Connection keep-alive 
Content-Type application/x-www-form-urlencoded 
Cookie PHPSESSID=5dkvr42f4it8pnnnqpesj6l413 
Host localhost 
Referer http://localhost/mifa/Suche.php 
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:13.0) Gecko/20100101 Firefox/13.0.1 
charset utf-8 

这里的响应头

Cache-Control max-age=3600 
Connection Keep-Alive 
Content-Type text/html 
Date Thu, 05 Jul 2012 15:28:22 GMT 
Expires Thu, 05 Jul 2012 16:28:22 GMT 
Keep-Alive timeout=5, max=91 
Pragma cache 
Server Apache/2.2.21 (Win32) mod_ssl/2.2.21 OpenSSL/1.0.0e PHP/5.3.8 mod_perl/2.0.4 Perl/v5.10.1 
Transfer-Encoding chunked 
X-Powered-By PHP/5.3.8 

我需要改变什么?

EDIT

显然,只有IE不缓存控制最大年龄= 0附加到该请求。

这里是请求的JS功能

url = "includes/Orte.php"; 
obj.onreadystatechange = rState; 
obj.open("GET", url, true); 
obj.setRequestHeader("Pragma", ""); 
obj.setRequestHeader("Cache-Control", ""); 
obj.setRequestHeader("charset", "utf-8"); 
obj.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
obj.setRequestHeader("Connection", "close"); 
obj.send(); 

function rState(){ 
    if(obj.readyState == 4){ 
     if (obj.status == 200){ 
      //alert("Response Text Ajax:\n" + obj.responseText + "\nEnd Response Text"); 
     } 
    } 
} 
+0

您可以通过在第二个随后的请求中发送一个HTTP 304 Not modified来实现,以确保浏览器不再询问。尽管设置了正确的缓存日期/时间等,但我相信某些浏览器会再次请求文件。 – fdomig 2012-07-05 15:35:01

回答

2

请求中的Cache-Control: max-age=0头信息意味着你问你的浏览器中刷新页面,所以他只是忽略缓存。

访问不刷新页面(例如,集中地址栏和回车)来避免这种情况。另外,如果页面位于HTTPS URL上,则可能必须将public添加到Cache-Control标头,否则某些浏览器将不会缓存它。

+0

你说得对,只有IE不会追加max-age = 0。 我该如何解决这个问题?我发布了上面的JS代码。你知道ff和chrome插入哪个头部? – ellow7 2012-07-05 16:10:20

0

两件事情浮现在脑海中的最后一次修改的头,并使用的.htaccess缓存控制。后者适用于广泛的类型,但您可以仅将它用于一个文件夹,并将该文件单独存放在一个文件夹中。

header("Last-Modified: ... "); 
+0

“Last-Modified”会触发浏览器在其下一个请求中发送“If-Modified-Since”;脚本将不得不解析并可能以'304 Not Modified'状态回复。这将阻止浏览器下载整个内容,但不会执行请求。 – arnaud576875 2012-07-05 15:47:11