$. getJSON 返回 IE8中的缓存数据

目前我正在使用 ASP.net MVC 和 JQuery。我遇到过一些不合常理的行为。

我正在调用 JQuery 的 $.getJSON函数来填充一些 div。事件在 $(document).ready事件上被触发。

有一个小的 AJAX.BeginForm,它添加了另一个值,以便在填充 div 时使用。它正确地调用远程函数,并在成功时调用原来的 javascript 函数来重新填充 div。

这就是奇怪的地方: 在 FireFox 和 Chrome 中,所有的东西都可以工作。但是在 IE8(Beta)中,第二次调用填充 Div 脚本(调用 $。GetJSON 函数)获取缓存数据并且不要求服务器!

希望这个问题是有意义的: 简而言之——为什么 $.getJSON会得到缓存数据?为什么它只影响 IE8?

46587 次浏览

You may need to send a cache-breaker.

I would recommend using $.ajax( { cache: no }) just in case ( adds a random suffix to the get request)

( I tend to use $.ajax everywhere these days, more tuneable )

Thanks Kent for your answer. Using $.ajax('{ cache: no }'); worked perfectly. [edit]

Or at least I thought i did. Seems that the jquery $.getJSON isn't reading any changes made to the $.ajax object.

The solution that ended up working was to add a new parameter manually

var noCache = Date();
$.getJSON("/somepage/someaction", { "noCache": noCache }, Callback);

the date resolution is only to the minute; which effectively means this solution still caches for upto one minute. This is acceptable for my purposes.

Just to let you know, Firefox and Chrome consider all Ajax request as non-cachable. IE (all versions) treat Ajax call just as other web request. That's why you see this behavior.
How to force IE to download data at each request:

  • As you said, use 'cache' or 'nocache' option in JQuery
  • Add a random parameter to the request (ugly, but works :))
  • On server side, set cachability (for example using an attribute, see below)

Code:

public class NoCacheAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext context)
{
context.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
}
}

This is how it worked for me...

$.ajaxSetup({ cache: false });
$.getJSON("/MyQueryUrl",function(data,item) {
// do stuff with callback data
$.ajaxSetup({ cache: true });
});

If you're using ASP.net MVC, consider adding an extension method to easily implement no caching like so:

    public static void NoCache(this HttpResponse Response)
{
Response.Cache.SetNoStore();
Response.Cache.SetExpires(DateTime.MinValue);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetValidUntilExpires(false);


Response.Expires = -1;
Response.ExpiresAbsolute = DateTime.MinValue;
Response.AddHeader("Cache-Control", "no-cache");
Response.AddHeader("Pragma", "no-cache");
}

I solved this same problem by placing the following attribute on the Action in the Controller:

[OutputCache(Duration = 0, VaryByParam = "None")]

Ready for THE answer ?

http://lestopher.tumblr.com/post/21742012438/if-youre-using-ie8-and-getjson

So, just add

jQuery.support.cors = true;

at the beginning of your script and BANG it works !