如何使用jquery将ajax响应存储在浏览器缓存中

How to store the ajax response in browser cache with jquery

本文关键字:浏览器 缓存 存储 响应 何使用 jquery ajax      更新时间:2023-09-26

我正在尝试将ajax响应存储在浏览器缓存中。我知道只为类似url的(example.com)存储它,但我想存储具有类似url的数据(example.com?xyz=abc%20efg&mno=hjk)。

我的代码:

beforeSend: function () {
                var addC=url;          // I want to add data also with this url
                console.log(addC);
                if (localCache.exist(addC)) {
                    printRes(localCache.get(url));
                    console.log("cached values");
                    return false;
                }
                return true;
            },

var localCache = {
    data: {},
    remove: function (url) {
        delete localCache.data[url];
    },
    exist: function (url) {
        return localCache.data.hasOwnProperty(url) && localCache.data[url] !== null;
    },
    get: function (url) {
        console.log('Getting in cache for url' + url);
        return localCache.data[url];
    },
    set: function (url, cachedData, callback) {
        localCache.remove(url);
        localCache.data[url] = cachedData;
        if ($.isFunction(callback)) callback(cachedData);
    }
};

请任何人帮我解决这个问题。

通过从MDN我认为你做错了。如果要将ajax响应CACHE属性缓存到true在ajax调用中,还要确保从服务器提供正确的缓存过期标头。而且【来自MDN】

永远不要使用传统的GET参数访问缓存的文件(就像其他缓存的一样-page.html?parameterName=值)。这将使浏览器绕过缓存并尝试获取它来自网络。要链接到具有在JavaScript中解析的参数的缓存资源,请使用链接的散列部分中的参数,例如其他缓存的page.html#什么?parameterName=值。

如果您正在寻找本地存储〔键值存储〕

globalStorage['cache_1'].setItem("key",data);