ariagno
ariagno

Reputation: 601

How to cache a JSON response?

I have a JSON file that is used to show prices. The JSON file only refreshes every 30 min server side, but when the client refreshes, he just gets the same version. Is there a way just to have the JSON file to have an expiration date, then re download it, instead of having to keep on download it?

Upvotes: 0

Views: 598

Answers (2)

Porizm
Porizm

Reputation: 533

Put this at the top of your php file that you are calling via ajax:

header("Cache-Control: max-age=1800");
header("Cache-Control: public", false);

this will let the browser to cache the file for 1800 seconds.

if you are using jQuery, don't forget to turn on the cache property:

$.ajax({url:"yourfile.php",cache:true})

Upvotes: 0

Todd Goodwin
Todd Goodwin

Reputation: 29

You could set your server up to return a 304 - Not Modified response if the file has not changed since the date that the browser has stored in its cache for that file. Basically, when a client requests a document, it can send a "If-Modified-Since" date in the request header. If the file has not changed since that date, the server will respond with a 304 - Not Modified response and the client will use the cached version instead.

Upvotes: 1

Related Questions