如何在浏览器中缓存Ajax响应并从缓存浏览器中检索值

时间:2018-10-10 11:37:52

标签: javascript jquery caching browser-cache

我想将Ajax响应缓存到浏览器数据库中,以便可以从同一应用程序的另一个网页检索响应。

到目前为止,我已经尝试过,但是我无法从浏览器缓存中检索数据。 任何帮助将不胜感激

这是我的setting.js

appsetting = {
service1: 'http://localhost:59190/api/Settings/GetConfigurationSettings',
settingsdata: {},
savesettings: function (data) {
    //alert('success');
    console.log(data);
    appsetting.settingsdata = data;
},
getsettings: function () {
    var token = { 'token': '00000000-0000-0000-0000-000000000000' };
    DBconnection.fetchdata('GET', appsetting.service1, appsetting.savesettings, function () { console.log('Cannot fetch pos') }, token, true);
}

}

这是ajaxcall.js

DBconnection = {
localCache: {
    timeout: 30000,
    data: {},
    remove: function (url) {
        delete DBconnection.localCache.data[url];
    },
    exist: function (url) {
        return !!DBconnection.localCache.data[url] && ((new Date().getTime() - DBconnection.localCache.data[url]._) < DBconnection.localCache.timeout);
    },
    get: function (url) {
        console.log('Getting in cache for url' + url);
        return DBconnection.localCache.data[url].data;
    },
    set: function (url, cachedData, callback) {
        DBconnection.localCache.remove(url);
        DBconnection.localCache.data[url] = {
            _: new Date().getTime(),
            data: cachedData
        };
        if ($.isFunction(callback)) callback(cachedData);
    }
},

fetchdata: function (typeofcall, url, success, failure, header, cachedata) {
    $.ajax({
        type: typeofcall,
        url: url,
        dataType: 'json',
        failure: failure,
        success: success,
        headers: header,
        cache: cachedata
    });
    $.ajaxPrefilter(function (options, originalOptions, jqXHR) {
        if (options.cache) {
            var complete = originalOptions.complete || $.noop,
                url = originalOptions.url;
            //remove jQuery cache as we have our own localCache
            options.cache = false;
            options.beforeSend = function () {
                if (DBconnection.localCache.exist(url)) {
                    complete(DBconnection.localCache.get(url));
                    return false;
                }
                return true;
            };
            options.complete = function (data, textStatus) {
                DBconnection.localCache.set(url, data, complete);
            };
        }
    });
}

}

在我的网页上,我正试图像这样

var setting = appsetting.getsettings();
console.log(setting);

但是我得到不确定的结果。

0 个答案:

没有答案