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上可用。
- Chrome扩展-缓存JSON文件1天
- 向ajax json请求添加缓存
- JQuery 如何读取 JSON 缓存
- 从索引数据库中的 ajax 调用缓存 JSON,检查更改
- 在客户端缓存大量 json 结果
- 在AngularJS中缓存国际化JSON数据
- 缓存通过PHP/AAJX/JSON/jQuery加载的动态图像
- .json文件的HTML5应用程序缓存
- 如何缓存ajax json对象以在图表中使用
- 在客户端上缓存JSON数组
- 缓存一个“;深“;使用GUID作为键的JSON对象
- 可以缓存JSON以增加性能/加载时间
- AngularJS.使用缓存时,防止加载JSON数据两次
- 如何为JSON清除缓存
- 如何避免过多的ajax调用和在客户端缓存json数据
- 从Ajax请求中同时使用缓存和非缓存JSON
- 有没有办法为AngularJS JSON请求($http/$resource)使用浏览器缓存?
- 用localStorage缓存每个JSON搜索查询
- D3.Json设置缓存为false
- jQuery json缓存,是否有办法改变时间戳url键