JQuery 如何读取 JSON 缓存


JQuery how to read json cache?

根据这个答案,我为我的json数据设置了缓存:

session_start();
if(isset($_SESSION['dataCache'])) {
    echo json_encode($_SESSION['dataCache']);
} else {
    $file = 'data.json';
    if (!is_file($file) || !is_readable($file)) {
        die("File not accessible.");
    }
    $contents = file_get_contents($file);
    $_SESSION['dataCache'] = json_decode($contents, true);
    echo $contents;
}

现在我想通过以下代码从 javascript 中读取缓存的内容:

if(localStorage.getItem("dataCache")) {
    data = JSON.parse(localStorage.getItem("dataCache"));

但是,问题是localStorage.getItem("dataCache")返回 null。

如何从 JavaScript 读取在 PHP 会话中创建的缓存?

问题是$_SESSION值只能在服务器端设置和使用。如果您希望在客户端JavaScript上使用此内容,则必须向PHP服务器发送请求以获取dataCache值,然后在local storage中对其进行设置。你可以像这样使用 ajax 调用

$.ajax({url: "getDataCache.php", success: function(result){
        localStorage.setItem('dataCache', result);
    }});

getDataCache.php你需要做这样的事情

echo json_encode($_SESSION['dataCache']);

然后

if(localStorage.getItem("dataCache")) {
    data = JSON.parse(localStorage.getItem("dataCache"));

将工作

关于这个问题的一篇好文章 http://www.devshed.com/c/a/php/html5-client-side-cache-in-php/

希望对:)有所帮助

$_SESSION[]将存储在服务器端(php)。

如果你想通过JavaScript(客户端)访问它,那么使用Ajax返回JSON,然后用你的JavaScript解析它。如果您需要浏览器保留副本,请在从服务器检索副本后将其存储在localStorage中。

在本文中,您提到的正确答案分为两部分。服务器端解释了如何将信息添加到 $_SESSION 并发送回查看。客户端说明如何获取该信息并将其存储在客户端缓存中。您错过了客户端。答案是谈论 ajax 调用,尽管其中 responseText 是一个 json,您需要将其转换为字符串。这部分

$.ajax({
    ...
    success: function (res) {
        localStorage.setItem("dataCache", JSON.stringify(res));
    },
    ...
});

然后,您可以稍后通过以下方式获取缓存的数据

if(localStorage.getItem("dataCache")) {
    data = JSON.parse(localStorage.getItem("dataCache"));
} else {
    // Make ajax call, fetch object and store in localStorage in the success or done callbacks as described above
}

请注意,在这一部分中,您实际上测试缓存上是否有任何内容,否则发送 ajax 调用获取信息并存储在缓存中。所以它会像波纹管一样

if(localStorage.getItem("dataCache")) {
    data = JSON.parse(localStorage.getItem("dataCache")); // get from cache
} else {
    $.ajax({
        ...
        success: function (res) {
            var dataToCache = JSON.stringify(res);
            localStorage.setItem("dataCache", dataToCache); // set cache
            data = JSON.parse(dataToCache); // set data
        },
        ...
    });
}

请注意,如参考文章中所述,此解决方案在HTML5上可用。