weixin_33735077 2015-08-14 23:55 采纳率: 0%
浏览 76

Ajax缓存,如何实现?

I've got this piece of jquery code that accesses a url via get and inserts the data to a container. How can I change it to actually cache the requested url and the returned data, so it won't load the url all over again if it's called more than once, but instead serve the cached data?

This is the code

_loadAjaxContents = function (href) {
  var dfr = new $.Deferred();

  $.get(href, function (data) {
    self.$expanderInner.html(data);
    dfr.resolve();
  });

  return dfr.promise();
}
  • 写回答

2条回答 默认 最新

  • weixin_33725722 2015-08-15 00:50
    关注

    well I made it by means of localstorage thanx to the link posted by aug.

    Here is the changed function

           _loadAjaxContents = function (href) {
          var dfr = new $.Deferred();
    
    
            function populateStorage(href,data){
                localStorage.setItem('url-' + href, data);
            }         
    
                var aValue = false;   
            if(aValue = localStorage.getItem('url-' + href)) {
                self.$expanderInner.html(aValue);
                dfr.resolve();                      
            } else {
                $.get(href, function (data) {
                    self.$expanderInner.html(data);
                    dfr.resolve();
                    populateStorage(href,data);
                });                 
            }  
    
          return dfr.promise();
        }
    
    评论

报告相同问题?