Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cache JSON object using jquery and retrieve it

Tags:

jquery

caching

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.

like image 362
newbie Avatar asked Oct 05 '12 15:10

newbie


2 Answers

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/

like image 83
nicholmikey Avatar answered Sep 30 '22 01:09

nicholmikey


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.

like image 36
Bahador Izadpanah Avatar answered Sep 30 '22 02:09

Bahador Izadpanah