【问题标题】:Storing Json in localStorage将 Json 存储在 localStorage 中
【发布时间】:2013-02-09 05:44:56
【问题描述】:

我想将搜索结果作为缓存存储在 localStorage 中。

我想将所有缓存存储为一个 localStorage 值:

localStorage.getItem('search-cache')

在其中我想要一个 JSON 对象,我可以添加属性并检索它们。 不幸的是,它不起作用,并且 localStorage 没有用 json 结果更新(它的值一直是'{}')。

我不是javascript专业人士,所以请指导我如何做好。

这是当前缓存结果的代码:

    var query = $(this).val();

    var cache = JSON.parse(localStorage.getItem('search-cache'));

    if (cache == null) {
        cache = '[{}]';
    }

    if (cache[query] == null) {

        $.getJSON('/api/guides/search?query=' + query, function (data) {
            $.each(data, function (index, guide) {
                $('#results').append('<li class="result-item">' + guide.Name + '</li>');
            });

            cache[query] = data;
            localStorage.setItem('search-cache', JSON.stringify(cache));
        });
    }
    else {
        $.each(JSON.parse(localStorage.getItem('search-cache')[query]), function (index, guide) {
            $('#results').append('<li class="result-item">' + guide.Name + '</li>');
        });

    }

【问题讨论】:

    标签: javascript jquery json local-storage getjson


    【解决方案1】:

    你的逻辑有些漏洞。

    var cache = JSON.parse(localStorage.getItem("..."));
    if (cache == null) { cache = "[{}]"; }
    

    好吧,如果项目 DID 存在,则您已将缓存设置为等于该对象。
    否则,您将缓存设置为等于字符串"[{}]"

    与其考虑如何构建本地存储,不如考虑如何构建结果列表。

    var cache_json = localStorage.getItem("search-cache"),
        search_cache = JSON.parse(cache_json) || {};
    
    var query = $("...").value(); // or whatever
    
    search_cache[query] = search_cache[query] || { results : [] };
    
    var list = $(......)
    list.each(function () {
        search_cache[query].results.push( /* whatever you want in your array */ );
    });
    
    
    cache_json = JSON.stringify(search_cache);
    localStorage.setItem("search-cache", query_json);
    

    【讨论】:

    • 谢谢,它确实有效!此外,我从你的回答中学到了其他东西——语法和 javascript 态度。
    【解决方案2】:

    因为,如果你的项目search-cache没有定义,你的缓存变量的初始化是不对的。

    你应该像这样初始化你的数组:

    if (cache == null) {
        cache = []; 
        cache[query] = null;
    }
    

    测试时满足条件

    if (cache[query] == null)
    

    但是,你需要像这样测试它:

    if(typeof cache[query] == 'undefined')
    

    【讨论】:

    • 感谢您的修复。我从中吸取了教训,但没有成功。
    【解决方案3】:

    cache 是一个对象而不是数组,像 cache = {} 一样初始化 其余代码似乎是正确的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-02
      • 1970-01-01
      • 2013-06-03
      • 2022-01-05
      • 1970-01-01
      • 2014-01-22
      • 1970-01-01
      • 2014-02-18
      相关资源
      最近更新 更多