Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cache a JSON object with HTML5

Tags:

json

html

First off I'd like to mention I'm an intern with little prior experience in the technical world so I am sorry if the answer to my question seems obvious. I have tried to find an answer for a couple days now and have little to show for it.

My project has been to develop a Phone Directory. What I am trying to do now is have a frequently searched box that shows the top ten searched names since the user started using the app. I am planing to make a JSON object with the following information and then client-side cache the result:

var myJSONObject = {"searched": [       {"firstname":firstName,"lastname":lastName,"PK":pk,"phone":phonenumber,"email":emailaddress,"bu":businessunit,"company":company,"building":building, "fax":fax, "timesvisited":"accumulator to keep track of visits to the name"}

] };

my head ache right now is figuring out how to cache the JSON object. I created a manifest file and I know how to cache certain files such as a css file, but how do you cache something such as the code listed above specifically so that the data is stored and can be brought up until the page on a second visit?

like image 360
Nick Brady Avatar asked Aug 02 '11 22:08

Nick Brady


2 Answers

You could use Local Storage, which is supported in Firefox 3.5, IE 8, and Chrome 4 and up. To save the cache to the local storage:

localStorage['jsoncache'] = JSON.stringify(myJSONObject);

To retrieve it:

myJSONObject = JSON.parse(localStorage['jsoncache']);

Notice how you can only store strings, not any kind of object, in local storage. You can change the jsoncache key to something else if you wish.

like image 121
Delan Azabani Avatar answered Sep 29 '22 14:09

Delan Azabani


I'm not completely how you create, maintain and retrieve the object, but If you load it via Ajax, you can use HTTP caching.

If you want to store it only locally then you can use localStorage (only newer browsers support that):

// Serialize and store
localeStorage['topten'] = JSON.stringify(myJSONObject)

// Retrieve and deserialize
var myJSONObject = JSON.parse(localeStorage['topten'])
like image 44
Jakub Roztocil Avatar answered Sep 29 '22 13:09

Jakub Roztocil