简体   繁体   中英

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?

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.

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})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM