How to set cache: false in jQuery.get call

jQuery.get() is a shorthand for jQuery.ajax() with a get call. But when I set cache:false in the data of the .get() call, what is sent to the server is a parameter called cache with a value of false. While my intention is to send a timestamp with the data to the server to prevent caching which is what happens if I use cache: false in jQuery.ajax data. How do I accomplish this without rewriting my jQuery.get calls to jQuery.ajax calls or using

$.ajaxSetup({
// Disable caching of AJAX responses
cache: false
});

update: Thanks everyone for the answers. You are all correct. However, I was hoping that there was a way to let the get call know that you do not want to cache, or send that value to the underlying .ajax() so it would know what to do with it.

I a. looking for a fourth way other than the three ways that have been identified so far:

  1. Doing it globally via ajaxSetup

  2. Using a .ajax call instead of a .get call

  3. Doing it manually by adding a new parameter holding a timestamp to your .get call.

I just thought that this capability should be built into the .get call.

118833 次浏览

对我来说,正确的方法是列出来的。不是 ajax就是 ajaxSetup。如果您真的想使用 get而不是 ajaxSetup,那么您可以创建您自己的参数并给它当前日期/时间的值。

不过我怀疑你不使用其他方法的动机。

自己添加参数。

$.get(url,{ "_": $.now() }, function(rdata){
console.log(rdata);
});

在 jQuery 3.0中,您现在可以这样做:

$.get({
url: url,
cache: false
}).then(function(rdata){
console.log(rdata);
});

我认为你必须使用 AJAX 方法来代替,它允许你关闭缓存:

$.ajax({
url: "test.html",
data: 'foo',
success: function(){
alert('bar');
},
cache: false
});

根据 JQuery 文档,.get()只使用 urldata(内容)、 dataTypesuccess回调作为参数。这里真正要做的是在发送 jqXHR 对象之前修改它。对于 .ajax(),这是用 beforeSend()方法完成的。但是因为 .get()是一条捷径,所以它不允许。

.ajax()调用切换到 .get()调用应该相对容易。毕竟,.get()只是 .ajax()的一个子集,因此可以使用 .ajax()的所有默认值(当然,除了 beforeSend())。

编辑:

看看吉文的回答:

哦,是的,忘记了 cache参数!虽然 beforeSend()对于添加其他头非常有用,但是内置的 cache参数在这里要简单得多。

我已经很晚了,但这可能对其他人有帮助。 我用 $碰到了同样的问题。我不想盲目地关闭缓存,我不喜欢时间戳补丁。 因此,经过一些研究,我发现你可以简单地使用 $。邮寄而不是 $。获取不使用缓存的。就这么简单。:)

Set cache: false in jQuery.get call using Under Method 设置缓存: false 在 jQuery.get 调用中使用 Under Method

使用新的 Date().getTime(),可以避免冲突,除非在同一毫秒内发生多个请求。

或者

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

$.ajaxSetup({ cache: false });

请注意,回调语法是 不赞成:

弃用通知书

成功()、 jqXHR.error ()和 jqXHR.complete ()回调 在 jQuery 1.5中引入的方法从 jQuery 1.8开始就不推荐了 使用 jqXHR.done ()为最终删除它们做好准备, Fall () ,而 jqXHR.always ()取而代之。

这是一个使用 promise接口的现代化解决方案

$.ajax({url: "...", cache: false}).done(function( data ) {
// data contains result
}).fail(function(err){
// error
});