Prasad Rajapaksha
Prasad Rajapaksha

Reputation: 6190

jQuery Cache JSON Request

I am developing HTML5 mobile app. I want to cache particular JSON request for 10 days using jQuery. I tried setting cache : true on the request. But I can't specify 10 days there. Is this possible to do? Or Do I need to use HTML5 local storage.

Upvotes: 0

Views: 1179

Answers (3)

James Black
James Black

Reputation: 41858

You could just store the json data, with a date, which will enable you to look up the cached data before calling to the server for an update.

You can use the local storage api in html5.

For some ideas on how to use it you can look at this question.

Storing Objects in HTML5 localStorage

To know if this will work on your target mobile devices you can look at this:

http://caniuse.com/#feat=namevalue-storage

So, you can do this:

var dtDateTime = new Date();
var intDateTime = dtDateTime.getTime();
var objJSON = {};
objJSON.datetime = intDateTime;
objJSON.data = myjson;
localStorage.setItem('cachedObject', JSON.stringify(objJSON));

Then you can just retrieve the object and check the date and decide if you need to reload the data.

I haven't tested this, but it should be close.

Upvotes: 2

Anna Brenden
Anna Brenden

Reputation: 3945

Setting cache: true should force the browser to follow the instructions specified in the HTTP response. To specify caching a response for 10 days, you can add this HTTP header from the server side: Cache-Control: max-age=864000.

Upvotes: 2

Ray Cheng
Ray Cheng

Reputation: 12576

is it because you should use domCache: true according to the doc.

Upvotes: 0

Related Questions