将Json存储在localStorage中

时间:2013-02-23 18:25:07

标签: javascript jquery json local-storage getjson

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

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

localStorage.getItem('search-cache')

在其中我希望有JSON对象,我可以添加属性并检索它们。 不幸的是它不起作用,并且localStorage没有使用json结果更新(其值保持为'{}')。

我不是一个javascript proffesional所以请指导我如何做好。

以下是缓存结果的当前代码:

    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>');
        });

    }

3 个答案:

答案 0 :(得分:3)

你的逻辑上有一些漏洞。

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);

答案 1 :(得分:1)

因为,如果未定义项目search-cache,则缓存变量的初始化不正确。

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

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

满足测试时的条件

if (cache[query] == null)

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

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

答案 2 :(得分:1)

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

相关问题