我在page.php上使用标准的php缓存脚本
$cache = 'the_location/'.$id.'.html';
$expire = time() -3600 ;
if(file_exists($cache) && filemtime($cache) > $expire)
{
readfile($cache);
} else {
ob_start();
// some stuff
$pages = ob_get_contents();
ob_end_flush();
$fd = fopen("$cache", "w");
if ($fd) {
fwrite($fd,$pages);
fclose($fd);
}
echo $pages ; }
在main_page.php上我正在加载page.php,如下所示:
$('#div').load('page.php?id=' + id);
如果我直接转到page.php?id = 1234页面被缓存,文件1234.html出现在'the_location'中 否则在main_page.php上没有任何反应......
非常感谢帮助!
编辑:一切都在main_page.php和page.php上运行,page.php正确加载到main_page.php但没有缓存,如果我通过浏览器加载page.php就会被缓存。
答案 0 :(得分:1)
我基本上尽可能地模拟了这个:
main_page.php:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head id="ctl00_Head1">
<script src="jquery-1.5.min.js"></script>
<script type="text/javascript">
var id = <?=$_GET['id']?>;
$(function(){
$('#div').load('page.php?id=' + id);
});
</script>
</head>
<body>
<div id="div">a</div>
</body>
</html>
page.php文件
<?php
$id = $_GET['id'];
$cache = 'the_location/'.$id.'.html';
$expire = time() -3600 ;
if(file_exists($cache) && filemtime($cache) > $expire)
{
readfile($cache);
} else {
ob_start();
echo 'This is a generated page';
$pages = ob_get_contents();
ob_end_clean();
$fd = fopen("$cache", "w");
if ($fd) {
fwrite($fd,$pages);
fclose($fd);
}
echo $pages;
}
这对我有用。我在处理代码时注意到的事情。
id
设置为php的$_GET['id']
$id = $_GET['id'];
ob_end_flush();
和echo $pages
是重复的(内容被刷新,然后在重新生成页面时显示两次),使用ob_end_clean()
或$pages = ob_get_flush()
。答案 1 :(得分:0)
您是否查看过使用firebug发送的请求? JQuery可能会在URL上附加一个cache-busting GET变量,从而破坏你的缓存:D