看起来,如果我使用$.get()加载动态内容,结果会缓存在浏览器中。
在QueryString中添加一些随机字符串似乎解决了这个问题(我使用new Date(). tostring()),但这感觉像是一个黑客。
还有别的办法吗? 或者,如果唯一字符串是实现这一点的唯一方法,除了new Date()还有其他建议吗?
看起来,如果我使用$.get()加载动态内容,结果会缓存在浏览器中。
在QueryString中添加一些随机字符串似乎解决了这个问题(我使用new Date(). tostring()),但这感觉像是一个黑客。
还有别的办法吗? 或者,如果唯一字符串是实现这一点的唯一方法,除了new Date()还有其他建议吗?
当前回答
正如@Athasach所说,根据jQuery文档,$. ajaxsetup ({cache:false})将不适用于GET和HEAD请求。
你最好从你的服务器发送回一个Cache-Control: no-cache头。它提供了更清晰的关注点分离。
当然,这对不属于项目的服务url不起作用。在这种情况下,您可以考虑从服务器代码代理第三方服务,而不是从客户端代码调用它。
其他回答
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.
我个人觉得查询字符串方法比试图在服务器上设置头文件更可靠——不能保证代理或浏览器不会缓存它(有些浏览器比其他浏览器更差——没有命名)。
我通常使用Math.random(),但我不认为使用日期有任何错误(您不应该以足够快的速度执行AJAX请求来两次获得相同的值)。
如果你正在使用。net ASP MVC,通过在end point函数上添加以下属性禁用控制器动作上的缓存:
[OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)]
用POST请求代替GET请求怎么样? (无论如何你应该……)
参考文档: http://api.jquery.com/jquery.ajax/
你可以使用缓存属性:
$.ajax({
method: "GET",
url: "/Home/AddProduct?",
data: { param1: value1, param2: value2},
cache: false,
success: function (result) {
// TODO
}
});