JQuery $ .getJSON异步解决方法 - 缓存ajax结果

时间:2016-07-29 09:11:50

标签: 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?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...
    )
}}

1 个答案:

答案 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...
            )
        }
    }
);