我缓存从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...
)
}}
'阿贾克斯是异步的,但我怎么避开that' - 不绕过它,拥抱它并学会使用它 –
或者,在页面最初生成时,通过服务器端代码提供初始数据。 –