I want to cache the following JSON object in the page so that I can retrieve it on another page.
var test = {
"lists":["list1","list2","list3","list4","list5"],
"maps": {
"key4":"value4","key3":"value3","key5":"value5","key2":"value2","key1":"value1"
},
"number1":123456789,
"numberarray1":[1,2,3,4,5,6,7,8,9],
"string1":"A",
"stringarray1":["A1","B1"]
}
How do I cache it and retrieve it again?
Is this possible? If not are there other ways that I can save my JSON object and then retrieve it on another page.
Thank you.
save that tasty cookie
$.cookie("test-data", JSON.stringify(test));
get that sweet cookie back
var test = JSON.parse($.cookie("test-data"));
http://www.electrictoolbox.com/jquery-cookies/
In addition to the provided answers, in more complex scenarios I would recommend using jStorage plugin.
Description from the website:
jStorage is a cross-browser key-value store database to store data locally in the browser - jStorage supports all major browsers, both in desktop (yes - even Internet Explorer 6) and in mobile. Additionally jStorage is library agnostic, it works well with any other JavaScript library on the same webpage, be it jQuery, Prototype, MooTools or something else. Though you still need to have either a third party library (Prototype, MooTools) or JSON2 on the page to support older IE versions.
jStorage supports storing Strings, Numbers, JavaScript objects, Arrays and even native XML nodes. jStorage also supports setting TTL values for auto expiring stored keys and - best of all - notifying other tabs/windows when a key has been changed or publishing/subscribing to events from the same or another tab/window, which makes jStorage also a local PubSub platform for web applications.
If jStorage is loaded on the page localStorage and sessionStorage polyfills are added to IE6 and IE7 in addition to regular $.jStorage methods. You can use regular setItem/getItem methods with the polyfills but getter/setters can be used as well - localStorage.mykey = myval; is absolutely valid with jStorage. The only downside is that you can't use onstorage event, you need to fall back to listenKeyChange instead.
jStorage is pretty small, about 10kB when minified and 4kB gzipped.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With