Javascript JQuery$.getJSON异步解决方案-缓存ajax结果
我缓存从ajax调用返回的JSON,然后显示缓存的结果。我的问题是,如果Ajax调用已经没有缓存,那么结果只会在刷新时显示。这取决于ajax是异步的,但我该如何解决这个问题呢?Ajax async:false已被弃用,因此这不是一个选项。$.getJSON.done()函数是否足够,还是有更好的方法 以下是我目前的代码:Javascript JQuery$.getJSON异步解决方案-缓存ajax结果,javascript,jquery,ajax,caching,asynchronous,Javascript,Jquery,Ajax,Caching,Asynchronous,我缓存从ajax调用返回的JSON,然后显示缓存的结果。我的问题是,如果Ajax调用已经没有缓存,那么结果只会在刷新时显示。这取决于ajax是异步的,但我该如何解决这个问题呢?Ajax async:false已被弃用,因此这不是一个选项。$.getJSON.done()函数是否足够,还是有更好的方法 以下是我目前的代码: if ((online === true)) { //get JSON $.getJSON(baseurl + '/wp-json/app/v2/files?f
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...
)
}}
只需简单地重写代码即可产生以下结果:
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...
)
}
}
);
ajax是异步的,但我如何绕过它呢
-不要绕过它,接受它,并学习如何交替使用它,在最初生成页面时通过服务器端代码提供初始数据。感谢您的回复,我已经尝试了您的代码,但不断获得,“index.html:387 Uncaught TypeError:无法读取null的属性'data',这是以下行://get cached JSON callback(null,cache['cat-'+cat]=JSON.parse(localStorage.getItem(cache['cat-'+cat]));那是因为我在localStorage.setItem
中逐字复制了您的代码…cat--
是错误的…应该是cat--
对不起,我不理解localStorage.setItem('cat--'+cat,JSON.stringify(缓存))这一行的内容
…它说的是cat-…2x-…而不是我说的cat-…直接从你的问题中复制是的,对不起,是我的错。但是复制代码时这是一个错误,我运行的不是我的实际代码。JSON正在缓存,但没有显示。看起来像var objCache=cachedata.data;是空的吗?