Ajax无法缓存

Yee*_*Yee 5 php ajax caching

我想在broswer中缓存数据,以便broswer不需要在几分钟内查询服务器.我添加了php缓存标题,但似乎不起作用.这是我的ajax代码和php代码:Ajax代码:

function myAjax(name, callback) {
    var url = './php/getJson.php?name=' + encodeURIComponent(name) + '&callback=?';
    jQuery.getJSON(url, function(data) {
        callback(data);
        jQuery.ajaxSetup({ cache: true });
    });
}
Run Code Online (Sandbox Code Playgroud)

PHP代码:

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

include_once('getData.php');

$output = $_GET['name'];

echo $_GET['callback'].'('.$output.')';
Run Code Online (Sandbox Code Playgroud)

感谢MitchSlenzai的帮助.这个问题解决了.该缓存:真正的选项应在所有Ajax查询之前设置老的jQuery库不支持缓存.因此,请确保您使用的是最新的jquery库

对于想要一个有效例子的人:

Ajax代码:

var callback = function(data) {
    alert("callback");
}
function myAjax(name) {
    var url = './php/getJson.php?name=' + encodeURIComponent(name) + '&callback=?';

    jQuery.ajaxSetup({ cache: true });
    jQuery.getJSON(url, function(data) {
        callback(data);
    });
}
Run Code Online (Sandbox Code Playgroud)

PHP代码:

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

$output = '{"eventList":["event1","test event"]}';

echo $_GET['callback'].'('.$output.')';
Run Code Online (Sandbox Code Playgroud)

Mit*_*ell 2

您将Last-Modified标题设置为一小时前,并将 设置max-age为一小时。

这意味着在您发送此数据时,它已经达到缓存允许的最长期限,并且必须重新发送任何后续请求。