[英]Storing Json in localStorage
I would like to store search results as cache in localStorage. 我想将搜索结果存储为localStorage中的缓存。
I would like to store all the cache as one localStorage value: 我想将所有缓存存储为一个localStorage值:
localStorage.getItem('search-cache')
Inside it I would like to have JSON object which I can add properties and retreive them. 在其中我想拥有JSON对象,我可以添加属性并检索它们。 Unfortunately it doesn't work and the localStorage is not updated with the json results (its value keep being
'{}'
). 不幸的是它不起作用,并且localStorage没有使用json结果更新(其值保持为
'{}'
)。
I am not a javascript proffesional so please guide me how to do it well. 我不是一个javascript proffesional所以请指导我如何做得好。
Here is the current code to cache results: 以下是缓存结果的当前代码:
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>');
});
}
You've got some holes in your logic. 你的逻辑上有一些漏洞。
var cache = JSON.parse(localStorage.getItem("..."));
if (cache == null) { cache = "[{}]"; }
Well, if the item DID exist, you've set cache to be equal to that object. 好吧,如果项目DID存在,您将缓存设置为等于该对象。
Otherwise, you've set cache to be equal to the string "[{}]"
. 否则,您将缓存设置为等于字符串
"[{}]"
。
Instead of thinking about how you're going to build your localstorage, think about how you're going to build your result list. 不要考虑如何构建本地存储,而是考虑如何构建结果列表。
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);
Because, in case of your item search-cache
is not defined, the initialization of your cache variable is not right. 因为,如果未定义项目
search-cache
,则缓存变量的初始化不正确。
You should initialize your array like this : 你应该像这样初始化你的数组:
if (cache == null) {
cache = [];
cache[query] = null;
}
To meet the condition when testing 满足测试条件
if (cache[query] == null)
however, you need to test it like this : 但是,你需要像这样测试它:
if(typeof cache[query] == 'undefined')
cache是一个对象而不是一个数组,初始化类似于cache = {}其余的代码似乎是正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.