Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control cache-control in ajax request

This might be a stupid question, but I searched a lot without any result. I know how to setup cache-control in server responses, but how can I change the cache control value in an ajax request? NOTE: I want the browser to use it's cache. I don't want it to get the updated json from the server ... this is the whole thing I'm trying to do.

enter image description here

like image 217
rramiii Avatar asked Oct 28 '15 11:10

rramiii


People also ask

Can AJAX requests be cached?

There is however a better solution – caching AJAX requests. Although we can use a standard caching solution provided by HTTP (yes, Ajax is cached by HTTP), there is a catch: It works for GET requests only (not POST). Furthermore, you cannot control cache expiration on the application side.

What is cache true in AJAX call?

cache:true is the default and does not always get the content from the cache. The cache-ability of an item on the browser is determined by: The response headers returned from the origin web server. If the headers indicate that content should not be cached then it won't be.

How do I set cache false in AJAX call?

The cache: false is used by developers to prevent all future AJAX requests from being cached, regardless of which jQuery method they use. We can use $. ajaxSetup({cache:false}); to apply the technique for all AJAX functions.


1 Answers

You can use headers property, like this:

$.ajax({
...
headers: {
     'Cache-Control': 'max-age=1000' 
}
...
});

Keep in mind that cache property has nothing in common with Cache-Control header, it's just a cache buster (appending ?_={timestamp} to GET parameters) and will only work correctly with GET and HEAD requests.

Anyway, something useful: How to set HTTP headers (for cache-control)?

like image 158
Kristian Vitozev Avatar answered Oct 21 '22 03:10

Kristian Vitozev