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

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

还有别的办法吗? 或者,如果唯一字符串是实现这一点的唯一方法,除了new Date()还有其他建议吗?


当前回答

对于那些在移动Safari上使用$. ajaxsetup()缓存选项的人来说,似乎必须为post使用时间戳,因为移动Safari也会缓存这个选项。根据$.ajax()的文档(你可以从$.ajaxSetup()跳转到该文档):

将cache设置为false将只对HEAD和GET请求有效。它通过将“_={timestamp}”附加到GET参数来工作。对于其他类型的请求,该参数不需要,除非在IE8中,当对一个已经被GET请求的URL进行POST时。

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

其他回答

基本上只需要添加cache:false;在ajax中,你认为内容会随着进程的进行而改变。在内容不会改变的地方,你可以省略这个。这样你每次都会得到新的响应

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

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

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.

参考文档: http://api.jquery.com/jquery.ajax/

你可以使用缓存属性:

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

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

$.get("myurl", myCallback)

你应该使用$。Ajax,它将允许你关闭缓存:

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