javascript - jQuery如何读取json缓存?

标签 javascript php jquery json caching

根据 this回答,我为我的 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 中创建的缓存?

最佳答案

问题是 $_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/

希望对你有帮助:)

关于javascript - jQuery如何读取json缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36051738/

相关文章:

javascript - 当 axios 中的 ajax 调用成功时执行某些操作 - 在 axios 中链接 then()

javascript - 类型错误 : Cannot read property 'getPrimaryDisplay' of undefined (screen. getPrimaryDisplay())

PHPSpreadsheet:如何获取加载的行数?

php - 如何从网络向应用程序发送 FCM 通知

javascript - 如何在添加一行后重置表的行类

javascript - ReactJs mapStateToProps

javascript - 如何在react中使用带有useState钩子(Hook)的回调

php - .htaccess AuthUserFile 基于环境的变量

android - 如何强制 Android Webview 在 DOM 更改时重新绘制?

javascript - 在vue js中调用v-checkbox onchange事件中的两个函数