防止jQuery AJAX调用结果的浏览器缓存

时间:2022-12-01 22:35:14

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

看起来如果我使用$.get()加载动态内容,结果会被缓存在浏览器中。

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

在QueryString中添加一些随机字符串似乎可以解决这个问题(我使用了new Date(). tostring())),但这感觉像是一个技巧。

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

还有别的办法吗?或者,如果唯一的字符串是实现此目的的唯一方法,除了new Date()之外,还有什么建议吗?

20 个解决方案

#1


205  

I use new Date().getTime(), which will avoid collisions unless you have multiple requests happening within the same millisecond:

我使用new Date().getTime(),它将避免冲突,除非在相同毫秒内发生多个请求:

$.get('/getdata?_=' + new Date().getTime(), function(data) {
    console.log(data); 
});

Edit: This answer is several years old. It still works (hence I haven't deleted it), but there are better/cleaner ways of achieving this now. My preference is for this method, but this answer is also useful if you want to disable caching for every request during the lifetime of a page.

编辑:这个答案已经有好几年的历史了。它仍然有效(因此我没有删除它),但是现在有更好的/更干净的方法来实现它。我倾向于使用这种方法,但是如果您希望在页面的生命周期中禁用每个请求的缓存,那么这个答案也很有用。

#2


483  

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

以下内容将防止缓存所有未来的AJAX请求,无论您使用哪种jQuery方法($)。,美元。ajax,等等)。

$.ajaxSetup({ cache: false });

#3


275  

JQuery's $.get() will cache the results. Instead of

JQuery的$.get()将缓存结果。而不是

$.get("myurl", myCallback)

you should use $.ajax, which will allow you to turn caching off:

您应该使用美元。ajax,允许您关闭缓存:

$.ajax({url: "myurl", success: myCallback, cache: false});

#4


19  

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

另一种方法是在生成ajax调用响应的代码中不提供服务器端缓存头:

response.setHeader( "Pragma", "no-cache" );
response.setHeader( "Cache-Control", "no-cache" );
response.setDateHeader( "Expires", 0 );

#5


13  

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

我通常使用Math.random(),但是我不认为使用日期有什么问题(您不应该以足够快的速度来获得相同的值两次)。

#6


13  

All the answers here leave a footprint on the requested URL which will show up in the access logs of server.

这里的所有答案都在所请求的URL上留下了一个足迹,该URL将显示在服务器的访问日志中。

I needed a header based solution with no side effect and I found it can be achieved by setting up the headers mentioned in How to control web page caching, across all browsers?.

我需要一个没有副作用的标题解决方案,我发现可以通过设置在所有浏览器中如何控制web页面缓存的标题来实现。

The results, working for Chrome at least, would be

结果是,至少对Chrome有效

$.ajax({
   url: url, 
   headers: {
     'Cache-Control': 'no-cache, no-store, must-revalidate', 
     'Pragma': 'no-cache', 
     'Expires': '0'
   }
});

#7


8  

Following the documentation: http://api.jquery.com/jquery.ajax/

以下文档:http://api.jquery.com/jquery.ajax/

you can use the cache property with:

您可以使用以下的缓存属性:

$.ajax({
    method: "GET",
    url: "/Home/AddProduct?",
    data: { param1: value1, param2: value2},
    cache: false,
    success: function (result) {
        // TODO
    }
});

#8


5  

The real question is why you need this to not be cached. If it should not be cached because it changes all the time, the server should specify to not cache the resource. If it just changes sometimes (because one of the resources it depends on can change), and if the client code has a way of knowing about it, it can append a dummy parameter to the url that is computed from some hash or last modified date of those resources (that's what we do in Microsoft Ajax script resources so they can be cached forever but new versions can still be served as they appear). If the client can't know of changes, the correct way should be for the server to handle HEAD requests properly and tell the client whether to use the cached version or not. Seems to me like appending a random parameter or telling from the client to never cache is wrong because cacheability is a property of the server resource, and so should be decided server-side. Another question to ask oneself is should this resource really be served through GET or should it go through POST? That is a question of semantics, but it also has security implications (there are attacks that work only if the server allows for GET). POST will not get cached.

真正的问题是为什么不需要缓存它。如果不应该缓存它,因为它一直在更改,服务器应该指定不缓存资源。如果它只是改变有时(因为一个资源取决于可以改变),如果客户端代码的了解它,它可以添加一个虚拟计算参数的url从一些散列或最后修改日期的那些资源(这是我们在微软Ajax脚本资源所以他们可以缓存永远但仍然可以作为新版本出现)。如果客户端不知道更改,服务器应该正确地处理HEAD请求,并告诉客户端是否使用缓存的版本。在我看来,添加随机参数或告诉客户端永远不要缓存是错误的,因为可缓存性是服务器资源的属性,因此应该在服务器端确定。另一个要问自己的问题是,这个资源是应该通过GET提供的,还是应该通过POST?这是一个语义问题,但它也有安全含义(只有在服务器允许GET时才会发生攻击)。POST不会被缓存。

#9


4  

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.

当然,“缓存破坏”技术将完成这项工作,但如果服务器向客户端表明不应该缓存响应,那么这将不会首先发生。在某些情况下,缓存响应是有益的,有时则不是。让服务器决定数据的正确生命周期。稍后您可能想要更改它。与UI代码中许多不同的地方相比,从服务器进行操作要容易得多。

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

当然,如果您对服务器没有控制权,这也没有帮助。

#10


4  

What about using a POST request instead of a GET...? (Which you should anyway...)

用POST请求而不是GET怎么样?(你应该不管怎样…)

#11


3  

Maybe you should look at $.ajax() instead (if you are using jQuery, which it looks like). Take a look at: http://docs.jquery.com/Ajax/jQuery.ajax#options and the option "cache".

也许您应该查看$.ajax()(如果您使用的是jQuery,看起来就是)。请看:http://docs.jquery.com/Ajax/jQuery.ajax#选项和“缓存”选项。

Another approach would be to look at how you cache things on the server side.

另一种方法是查看如何在服务器端缓存东西。

#12


3  

A small addition to the excellent answers given: If you're running with a non-ajax backup solution for users without javascript, you will have to get those server-side headers correct anyway. This is not impossible, although I understand those that give it up ;)

除了给出的优秀答案之外,还有一个小的补充:如果您正在为没有javascript的用户运行非ajax备份解决方案,那么无论如何您都必须使服务器端头正确。这并非不可能,尽管我理解那些放弃的人;

I'm sure there's another question on SO that will give you the full set of headers that are appropriate. I am not entirely conviced miceus reply covers all the bases 100%.

我肯定还有另一个问题,这会给你一套合适的标题。我还没有完全确定米修斯的回复100%涵盖了所有的基地。

#13


3  

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()):

对于在mobile Safari中使用$. ajaxsetup()的缓存选项的用户来说,您可能需要对文章使用时间戳,因为mobile Safari也会缓存这些内容。根据关于$.ajax()的文档(从$.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.

将缓存设置为false将只对HEAD和GET请求有效。它通过向GET参数添加“_={timestamp}”来工作。其他类型的请求都不需要这个参数,除了在IE8中,当一个POST被发送到一个已经被GET请求的URL时。

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

因此,在我上面提到的情况下,单独设置这个选项对您没有帮助。

#14


2  

Basically just add cache:false; in the ajax where you think the content will change as the progress go on. And the place where the content wont change there u can omit this. In this way u will get the new response every time

基本上只是添加缓存:错误;在ajax中,当进度继续时,您认为内容会发生变化。内容不会改变的地方,你可以忽略它。这样你每次都会得到新的回复

#15


2  

Internet Explorer’s Ajax Caching: What Are YOU Going To Do About It? suggests three approaches:

Internet Explorer的Ajax缓存:您打算怎么做?提出了三种方法:

  1. Add a cache busting token to the query string, like ?date=[timestamp]. In jQuery and YUI you can tell them to do this automatically.
  2. 向查询字符串添加缓存破坏令牌,如?date=[timestamp]。在jQuery和YUI中,您可以告诉他们自动执行。
  3. Use POST instead of a GET
  4. 用POST代替GET
  5. Send a HTTP response header that specifically forbids browsers to cache it
  6. 发送一个HTTP响应头,明确禁止浏览器缓存它

#16


2  

Now, it's easy to do it by enabling/disabling cache option in your ajax request, just like this

现在,通过在ajax请求中启用/禁用缓存选项很容易做到这一点,就像这样

$(function () {
    var url = 'your url goes here';
    $('#ajaxButton').click(function (e) {
        $.ajax({
            url: url,
            data: {
                test: 'value'
            },
                cache: true, //cache enabled, false to reverse
                complete: doSomething
            });
        });
    });
    //ToDo after ajax call finishes
    function doSomething(data) {
        console.log(data);
    }
});

#17


1  

If you are using IE 9, then you need to use the following in front of your controller class definition:

如果您使用的是IE 9,那么您需要在控制器类定义前面使用以下内容:

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]

public class TestController : Controller

公共类TestController:控制器

This will prevent the browser from caching.

这将防止浏览器缓存。

Details on this link: http://dougwilsonsa.wordpress.com/2011/04/29/disabling-ie9-ajax-response-caching-asp-net-mvc-3-jquery/

关于这个链接的详细信息:http://dougwilsonsa.wordpress.com/2011/04/29/disabling-ie9- ajax-responseing-asp-net -mvc-3-jquery/

Actually this solved my issue.

实际上这解决了我的问题。

#18


1  

As @Athasach said, according to the jQuery docs, $.ajaxSetup({cache:false}) will not work for other than GET and HEAD requests.

正如@Athasach所说,根据jQuery文档,$. ajaxsetup ({cache:false})只能用于GET和HEAD请求。

You are better off sending back a Cache-Control: no-cache header from your server anyway. It provides a cleaner separation of concerns.

最好还是从服务器上发回Cache-Control: no-cache头。它提供了更清晰的关注点分离。

Of course, this would not work for service urls that you do not belong to your project. In that case, you might consider proxying the third party service from server code rather than calling it from client code.

当然,这对于不属于您的项目的服务url是不起作用的。在这种情况下,您可以考虑从服务器代码代理第三方服务,而不是从客户机代码调用它。

#19


0  

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

如果您正在使用。net ASP MVC,通过在端点函数中添加以下属性来禁用控制器动作的缓存:[OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)]

#20


-3  

append Math.random() to the request url

将Math.random()附加到请求url

#1


205  

I use new Date().getTime(), which will avoid collisions unless you have multiple requests happening within the same millisecond:

我使用new Date().getTime(),它将避免冲突,除非在相同毫秒内发生多个请求:

$.get('/getdata?_=' + new Date().getTime(), function(data) {
    console.log(data); 
});

Edit: This answer is several years old. It still works (hence I haven't deleted it), but there are better/cleaner ways of achieving this now. My preference is for this method, but this answer is also useful if you want to disable caching for every request during the lifetime of a page.

编辑:这个答案已经有好几年的历史了。它仍然有效(因此我没有删除它),但是现在有更好的/更干净的方法来实现它。我倾向于使用这种方法,但是如果您希望在页面的生命周期中禁用每个请求的缓存,那么这个答案也很有用。

#2


483  

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

以下内容将防止缓存所有未来的AJAX请求,无论您使用哪种jQuery方法($)。,美元。ajax,等等)。

$.ajaxSetup({ cache: false });

#3


275  

JQuery's $.get() will cache the results. Instead of

JQuery的$.get()将缓存结果。而不是

$.get("myurl", myCallback)

you should use $.ajax, which will allow you to turn caching off:

您应该使用美元。ajax,允许您关闭缓存:

$.ajax({url: "myurl", success: myCallback, cache: false});

#4


19  

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

另一种方法是在生成ajax调用响应的代码中不提供服务器端缓存头:

response.setHeader( "Pragma", "no-cache" );
response.setHeader( "Cache-Control", "no-cache" );
response.setDateHeader( "Expires", 0 );

#5


13  

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

我通常使用Math.random(),但是我不认为使用日期有什么问题(您不应该以足够快的速度来获得相同的值两次)。

#6


13  

All the answers here leave a footprint on the requested URL which will show up in the access logs of server.

这里的所有答案都在所请求的URL上留下了一个足迹,该URL将显示在服务器的访问日志中。

I needed a header based solution with no side effect and I found it can be achieved by setting up the headers mentioned in How to control web page caching, across all browsers?.

我需要一个没有副作用的标题解决方案,我发现可以通过设置在所有浏览器中如何控制web页面缓存的标题来实现。

The results, working for Chrome at least, would be

结果是,至少对Chrome有效

$.ajax({
   url: url, 
   headers: {
     'Cache-Control': 'no-cache, no-store, must-revalidate', 
     'Pragma': 'no-cache', 
     'Expires': '0'
   }
});

#7


8  

Following the documentation: http://api.jquery.com/jquery.ajax/

以下文档:http://api.jquery.com/jquery.ajax/

you can use the cache property with:

您可以使用以下的缓存属性:

$.ajax({
    method: "GET",
    url: "/Home/AddProduct?",
    data: { param1: value1, param2: value2},
    cache: false,
    success: function (result) {
        // TODO
    }
});

#8


5  

The real question is why you need this to not be cached. If it should not be cached because it changes all the time, the server should specify to not cache the resource. If it just changes sometimes (because one of the resources it depends on can change), and if the client code has a way of knowing about it, it can append a dummy parameter to the url that is computed from some hash or last modified date of those resources (that's what we do in Microsoft Ajax script resources so they can be cached forever but new versions can still be served as they appear). If the client can't know of changes, the correct way should be for the server to handle HEAD requests properly and tell the client whether to use the cached version or not. Seems to me like appending a random parameter or telling from the client to never cache is wrong because cacheability is a property of the server resource, and so should be decided server-side. Another question to ask oneself is should this resource really be served through GET or should it go through POST? That is a question of semantics, but it also has security implications (there are attacks that work only if the server allows for GET). POST will not get cached.

真正的问题是为什么不需要缓存它。如果不应该缓存它,因为它一直在更改,服务器应该指定不缓存资源。如果它只是改变有时(因为一个资源取决于可以改变),如果客户端代码的了解它,它可以添加一个虚拟计算参数的url从一些散列或最后修改日期的那些资源(这是我们在微软Ajax脚本资源所以他们可以缓存永远但仍然可以作为新版本出现)。如果客户端不知道更改,服务器应该正确地处理HEAD请求,并告诉客户端是否使用缓存的版本。在我看来,添加随机参数或告诉客户端永远不要缓存是错误的,因为可缓存性是服务器资源的属性,因此应该在服务器端确定。另一个要问自己的问题是,这个资源是应该通过GET提供的,还是应该通过POST?这是一个语义问题,但它也有安全含义(只有在服务器允许GET时才会发生攻击)。POST不会被缓存。

#9


4  

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.

当然,“缓存破坏”技术将完成这项工作,但如果服务器向客户端表明不应该缓存响应,那么这将不会首先发生。在某些情况下,缓存响应是有益的,有时则不是。让服务器决定数据的正确生命周期。稍后您可能想要更改它。与UI代码中许多不同的地方相比,从服务器进行操作要容易得多。

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

当然,如果您对服务器没有控制权,这也没有帮助。

#10


4  

What about using a POST request instead of a GET...? (Which you should anyway...)

用POST请求而不是GET怎么样?(你应该不管怎样…)

#11


3  

Maybe you should look at $.ajax() instead (if you are using jQuery, which it looks like). Take a look at: http://docs.jquery.com/Ajax/jQuery.ajax#options and the option "cache".

也许您应该查看$.ajax()(如果您使用的是jQuery,看起来就是)。请看:http://docs.jquery.com/Ajax/jQuery.ajax#选项和“缓存”选项。

Another approach would be to look at how you cache things on the server side.

另一种方法是查看如何在服务器端缓存东西。

#12


3  

A small addition to the excellent answers given: If you're running with a non-ajax backup solution for users without javascript, you will have to get those server-side headers correct anyway. This is not impossible, although I understand those that give it up ;)

除了给出的优秀答案之外,还有一个小的补充:如果您正在为没有javascript的用户运行非ajax备份解决方案,那么无论如何您都必须使服务器端头正确。这并非不可能,尽管我理解那些放弃的人;

I'm sure there's another question on SO that will give you the full set of headers that are appropriate. I am not entirely conviced miceus reply covers all the bases 100%.

我肯定还有另一个问题,这会给你一套合适的标题。我还没有完全确定米修斯的回复100%涵盖了所有的基地。

#13


3  

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()):

对于在mobile Safari中使用$. ajaxsetup()的缓存选项的用户来说,您可能需要对文章使用时间戳,因为mobile Safari也会缓存这些内容。根据关于$.ajax()的文档(从$.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.

将缓存设置为false将只对HEAD和GET请求有效。它通过向GET参数添加“_={timestamp}”来工作。其他类型的请求都不需要这个参数,除了在IE8中,当一个POST被发送到一个已经被GET请求的URL时。

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

因此,在我上面提到的情况下,单独设置这个选项对您没有帮助。

#14


2  

Basically just add cache:false; in the ajax where you think the content will change as the progress go on. And the place where the content wont change there u can omit this. In this way u will get the new response every time

基本上只是添加缓存:错误;在ajax中,当进度继续时,您认为内容会发生变化。内容不会改变的地方,你可以忽略它。这样你每次都会得到新的回复

#15


2  

Internet Explorer’s Ajax Caching: What Are YOU Going To Do About It? suggests three approaches:

Internet Explorer的Ajax缓存:您打算怎么做?提出了三种方法:

  1. Add a cache busting token to the query string, like ?date=[timestamp]. In jQuery and YUI you can tell them to do this automatically.
  2. 向查询字符串添加缓存破坏令牌,如?date=[timestamp]。在jQuery和YUI中,您可以告诉他们自动执行。
  3. Use POST instead of a GET
  4. 用POST代替GET
  5. Send a HTTP response header that specifically forbids browsers to cache it
  6. 发送一个HTTP响应头,明确禁止浏览器缓存它

#16


2  

Now, it's easy to do it by enabling/disabling cache option in your ajax request, just like this

现在,通过在ajax请求中启用/禁用缓存选项很容易做到这一点,就像这样

$(function () {
    var url = 'your url goes here';
    $('#ajaxButton').click(function (e) {
        $.ajax({
            url: url,
            data: {
                test: 'value'
            },
                cache: true, //cache enabled, false to reverse
                complete: doSomething
            });
        });
    });
    //ToDo after ajax call finishes
    function doSomething(data) {
        console.log(data);
    }
});

#17


1  

If you are using IE 9, then you need to use the following in front of your controller class definition:

如果您使用的是IE 9,那么您需要在控制器类定义前面使用以下内容:

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]

public class TestController : Controller

公共类TestController:控制器

This will prevent the browser from caching.

这将防止浏览器缓存。

Details on this link: http://dougwilsonsa.wordpress.com/2011/04/29/disabling-ie9-ajax-response-caching-asp-net-mvc-3-jquery/

关于这个链接的详细信息:http://dougwilsonsa.wordpress.com/2011/04/29/disabling-ie9- ajax-responseing-asp-net -mvc-3-jquery/

Actually this solved my issue.

实际上这解决了我的问题。

#18


1  

As @Athasach said, according to the jQuery docs, $.ajaxSetup({cache:false}) will not work for other than GET and HEAD requests.

正如@Athasach所说,根据jQuery文档,$. ajaxsetup ({cache:false})只能用于GET和HEAD请求。

You are better off sending back a Cache-Control: no-cache header from your server anyway. It provides a cleaner separation of concerns.

最好还是从服务器上发回Cache-Control: no-cache头。它提供了更清晰的关注点分离。

Of course, this would not work for service urls that you do not belong to your project. In that case, you might consider proxying the third party service from server code rather than calling it from client code.

当然,这对于不属于您的项目的服务url是不起作用的。在这种情况下,您可以考虑从服务器代码代理第三方服务,而不是从客户机代码调用它。

#19


0  

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

如果您正在使用。net ASP MVC,通过在端点函数中添加以下属性来禁用控制器动作的缓存:[OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)]

#20


-3  

append Math.random() to the request url

将Math.random()附加到请求url