根据 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({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/