简体   繁体   中英

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.

在此处输入图片说明

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

The real answer is that when you see Cache-Control: max-age=0 in the Network panel then this is most probably something browser is doing to avoid cache. This is not something jQuery is doing by default . So no point in changing headers. So you can simply use $.getJSON() and HTTP cache will work...

So just turn off Disable Cache feature in devtools and you should be fine (as already noted in comments from kav).

But there is also another gotcha. Cache-control headers will only work for plain 200 request (success). Most errors will not be cached in Firefox. No matter what your server says, Firefox will ignore Cache-control headers in the response. So no matter what you do Firefox will not cache 404 nor 400 requests. You can use 410 (Gone) instead of 404. But that also need to be done server-side, not in AJAX request (so in response headers, not in request headers).

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