如何缓存ajax json对象以在图表中使用
How to cache ajax json object for use in chart
我使用的是morris.js图表库,目前我使用ajax请求通过php获取json对象。
我想做的是缓存响应,如果json已经缓存,那么在加载页面时使用该数据,而不是进行另一个ajax调用。
我对ajax的理解是有限的,我尝试过sessionStorage
,但生成图表的功能在ajax完成之前就运行了。
任何建议都将是伟大的
感谢
var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
var getAreaData = (function () {
var cache = {}; // results will be cached in this object
return function (callback) {
if (cache != null) { // if exist on cache
callback(cache);
return;
}
// doesn't exists on cache, make Ajax request and cache it
$.get(baseUrl+"/main/orderChannel", function (data) {
cache= data; // store the returned data
callback(data);
console.log(data);
});
};
})();
getAreaData(function (data) {
console.log(data);
});
当您使用JQuery时,您可以让回调变得非常简单,只需使用promise即可返回。你可以做得简单一点,比如:
(function($) {
function getAreaData(url) {
var def = $.Deferred();
if (getAreaData.cache) {
// call it at the next possible time
setTimeout(function() { def.resolve(getAreaData.cache) }, 0);
return def;
}
$.get(url).done(function(data) {
// cache the result as a property of the getAreaData function
getAreaData.cache = data;
def.resolve(data);
}).fail(def.reject);
return def;
}
// uncomment this line to see how the cache would react when enabled
//getAreaData.cache = { key: 'I am an object' };
$.getAreaData = getAreaData;
})(jQuery);
$.getAreaData('#/items')
.done(function(data) {
console.log('I succeeded with ', data);
})
.fail(function(error) {
console.log('I failed with ', error);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
相关文章:
- jQuery匹配JSON对象的部分文本
- 如何在Javascript中将JSon对象转换为数组
- 我可以在json对象中添加一个函数吗
- 使用JS将数组转换为json对象
- 我应该如何将响应数据保存在对象(json)中以获得更好的操作和性能
- 用javascript从列表对象(JSON的)构建diffrent选项卡
- php请求带有多个对象json-jquery
- AngularJS,过滤器:如何将一个巨大的对象(JSON)变成一个数组
- 动态属性对象 - JSON
- JavaScript 对象 (JSON) 中的动态设置值
- 从数组查询获取对象 JSON 值时出错
- 使用jQuerygetJSON将多维对象JSON转换为HTML
- 需要从 Angular JS 应用程序中的另一个 JSON 对象数组填充 JSON 数组的每个对象 JSON 对象数组
- 嵌套对象JSON排序JavaScript
- PHP在MySQL中保存来自Javascript的对象"JSON.stringify"通过Ajax
- 将JavaScript对象/ JSON转换为PHP数组
- JSON对象.JSON对象内部
- 访问对象的对象- JSON API
- 数组到对象JSON
- Message":"传入的无效对象(JSON数据格式化问题)