看起来,如果我使用$.get()加载动态内容,结果会缓存在浏览器中。
在QueryString中添加一些随机字符串似乎解决了这个问题(我使用new Date(). tostring()),但这感觉像是一个黑客。
还有别的办法吗? 或者,如果唯一字符串是实现这一点的唯一方法,除了new Date()还有其他建议吗?
看起来,如果我使用$.get()加载动态内容,结果会缓存在浏览器中。
在QueryString中添加一些随机字符串似乎解决了这个问题(我使用new Date(). tostring()),但这感觉像是一个黑客。
还有别的办法吗? 或者,如果唯一字符串是实现这一点的唯一方法,除了new Date()还有其他建议吗?
当前回答
添加标题
headers: {
'Cache-Control':'no-cache'
}
其他回答
当然,“缓存破坏”技术可以完成这项工作,但是如果服务器指示客户机不应该缓存响应,那么这种情况一开始就不会发生。在某些情况下缓存响应是有益的,而在某些情况下则不然。让服务器决定数据的正确生命周期。稍后您可能想要更改它。在服务器上比在UI代码的其他地方要容易得多。
当然,如果您无法控制服务器,这是没有帮助的。
添加标题
headers: {
'Cache-Control':'no-cache'
}
将Math.random()追加到请求url
JQuery的$.get()将缓存结果。而不是
$.get("myurl", myCallback)
你应该使用$。Ajax,它将允许你关闭缓存:
$.ajax({url: "myurl", success: myCallback, cache: false});
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.