看起来,如果我使用$.get()加载动态内容,结果会缓存在浏览器中。
在QueryString中添加一些随机字符串似乎解决了这个问题(我使用new Date(). tostring()),但这感觉像是一个黑客。
还有别的办法吗? 或者,如果唯一字符串是实现这一点的唯一方法,除了new Date()还有其他建议吗?
看起来,如果我使用$.get()加载动态内容,结果会缓存在浏览器中。
在QueryString中添加一些随机字符串似乎解决了这个问题(我使用new Date(). tostring()),但这感觉像是一个黑客。
还有别的办法吗? 或者,如果唯一字符串是实现这一点的唯一方法,除了new Date()还有其他建议吗?
当前回答
参考文档: http://api.jquery.com/jquery.ajax/
你可以使用缓存属性:
$.ajax({
method: "GET",
url: "/Home/AddProduct?",
data: { param1: value1, param2: value2},
cache: false,
success: function (result) {
// TODO
}
});
其他回答
我使用new Date().getTime(),这将避免冲突,除非你有多个请求发生在同一毫秒内:
$.get('/getdata?_=' + new Date().getTime(), function(data) {
console.log(data);
});
编辑:这个答案是几年前的了。它仍然可以工作(因此我没有删除它),但现在有更好/更干净的方法来实现这一点。我倾向于使用这种方法,但是如果您想在页面的生命周期内为每个请求禁用缓存,那么这个答案也很有用。
JQuery的$.get()将缓存结果。而不是
$.get("myurl", myCallback)
你应该使用$。Ajax,它将允许你关闭缓存:
$.ajax({url: "myurl", success: myCallback, cache: false});
也许你应该看看$.ajax()(如果你使用的是jQuery,它看起来就像jQuery)。 看一下:http://docs.jquery.com/Ajax/jQuery.ajax#options和选项“缓存”。
另一种方法是研究如何在服务器端缓存内容。
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.
除了给出的优秀答案,还有一个小小的补充:如果您正在为没有javascript的用户运行非ajax备份解决方案,那么无论如何您都必须使服务器端头正确。这不是不可能的,尽管我理解那些放弃它的人;)
我相信还有另一个关于SO的问题会给你全套合适的标题。我不完全相信老鼠的回答涵盖了所有的基础100%。