2016-07-29 62 views
1

我缓存从ajax调用返回的JSON,然后显示缓存中的结果。我的问题是,如果没有用于该Ajax调用的缓存,则结果仅在刷新时显示。这是由于ajax是异步的,但我该如何解决这个问题呢? Ajax async:false已被弃用,所以这不是一个选项。 $ .getJSON .done()函数是否足够或有更好的方法?

这是到目前为止我的代码:

if ((online === true)) { 
    //get JSON 
    $.getJSON(baseurl + '/wp-json/app/v2/files?filter[category]' + cat + '&per_page=100', function(jd) { 
     //cache JSON 
     var cache = { 
      date: new Date(), 
      data: JSON.stringify(jd) 
     }; 
     localStorage.setItem('cat-' + cat, JSON.stringify(cache)); 
    }); 
    //if not online and no cached file 
} else if ((online === false) && (!cache['cat-' + cat])) { 
    alert('There are no cached files. You need to be online.'); 
} 

//get cached JSON 
cache['cat-' + cat] = JSON.parse(localStorage.getItem('cat-' + cat)); 
var objCache = cache['cat-' + cat].data; 
objCache = JSON.parse(objCache); //Parse string to json 
//display JSON results from cache 
$.each(objCache, function(i, jd) { 
    var thumb = jd.file_thumbnail.sizes.medium; 
    //.....etc... 
    ) 
}} 
+3

'阿贾克斯是异步的,但我怎么避开that' - 不绕过它,拥抱它并学会使用它 –

+0

或者,在页面最初生成时,通过服务器端代码提供初始数据。 –

回答

1

代码的简单改写产生如下:

function cacheAsCacheCan(cat, callback) { 
    if (online === true) { 
     //get JSON 
     $.getJSON(baseurl + '/wp-json/app/v2/files?filter[category]' + cat + '&per_page=100', function(jd) { 
      //cache JSON 
      var cache = { 
       date: new Date(), 
       data: JSON.stringify(jd) 
      }; 
      localStorage.setItem('cat--' + cat, JSON.stringify(cache)); 
     }); 
     //if not online and no cached file 
    } else if ((online === false) && (!cache['cat-' + cat])) { 
     callback('There are no cached files. You need to be online.'); 
     return; 
    } 
    //get cached JSON 
    callback(null, cache['cat-' + cat] = JSON.parse(localStorage.getItem('cat-' + cat))); 
} 

cacheAsCacheCan('someCat', function(error, cachedata) { 
    if(error) { 
     alert(error); 
    } else { 
     var objCache = cachedata.data; 
     objCache = JSON.parse(objCache); //Parse string to json 
     //display JSON results from cache 
     $.each(objCache, function(i, jd) { 
       var thumb = jd.file_thumbnail.sizes.medium; 
       //.....etc... 
      ) 
     } 
    } 
); 
+0

感谢您的反应,我已经尝试过你的代码,但不断收到,“index.html:387 Uncaught TypeError:无法读取null属性'数据'这是以下行://获取缓存JSON callback(null,cache ['cat-'+ cat] = JSON.parse(localStorage.getItem(cache ['cat-'+ cat]))); – LeeTee

+0

这是因为我复制了你的代码逐字...'cat - '在'localStorage.setItem'中是错误的......应该是'cat -' –

+0

对不起,我不明白 – LeeTee