Prevent browser caching of jQuery AJAX call result

2018-12-31 09:07发布

It looks like if I load dynamic content using $.get(), the result is cached in browser.

Adding some random string in QueryString seems to solve this issue (I use new Date().toString()), but this feels like a hack.

Is there any other way to achieve this? Or, if unique string is the only way to achieve this, any suggestions other than new Date()?

20条回答
谁念西风独自凉
2楼-- · 2018-12-31 09:08

another way is to provide no cache headers from serverside in the code that generates the response to ajax call:

response.setHeader( "Pragma", "no-cache" );
response.setHeader( "Cache-Control", "no-cache" );
response.setDateHeader( "Expires", 0 );
查看更多
墨雨无痕
3楼-- · 2018-12-31 09:10

Of course "cache-breaking" techniques will get the job done, but this would not happen in the first place if the server indicated to the client that the response should not be cached. In some cases it is beneficial to cache responses, some times not. Let the server decide the correct lifetime of the data. You may want to change it later. Much easier to do from the server than from many different places in your UI code.

Of course this doesn't help if you have no control over the server.

查看更多
梦该遗忘
4楼-- · 2018-12-31 09:11

Personally I feel that the query string method is more reliable than trying to set headers on the server - there's no guarantee that a proxy or browser won't just cache it anyway (some browsers are worse than others - naming no names).

I usually use Math.random() but I don't see anything wrong with using the date (you shouldn't be doing AJAX requests fast enough to get the same value twice).

查看更多
像晚风撩人
5楼-- · 2018-12-31 09:11

For those of you using the cache option of $.ajaxSetup() on mobile Safari, it appears that you may have to use a timestamp for POSTs, since mobile Safari caches that too. According to the documentation on $.ajax() (which you are directed to from $.ajaxSetup()):

Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET.

So setting that option alone won't help you in the case I mentioned above.

查看更多
皆成旧梦
6楼-- · 2018-12-31 09:11

If you are using .net ASP MVC, disable the caching on the controller action by adding the following attribute on the end point function: [OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)]

查看更多
倾城一夜雪
7楼-- · 2018-12-31 09:12

The following will prevent all future AJAX requests from being cached, regardless of which jQuery method you use ($.get, $.ajax, etc.)

$.ajaxSetup({ cache: false });
查看更多
登录 后发表回答