如何缓存ajax json对象以在图表中使用

How to cache ajax json object for use in chart

本文关键字:对象 json 何缓存 缓存 ajax      更新时间:2023-09-26

我使用的是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>