Cache a JSON object with HTML5
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 hea开发者_Go百科d 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?
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.
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'])
精彩评论