$.getJSON devuelve datos almacenados en caché en IE8
Estoy jugando con ASP.net MVC y jQuery en este momento. Me he encontrado con un comportamiento que no parece tener sentido.
Estoy llamando a la función $.getJSON
de jQuery para rellenar algunos div. El evento se activa en el evento $(document).ready
. Esto funciona perfectamente.
Hay un pequeño AJAX.BeginForm
que agrega otro valor que se utilizará al rellenar los divs. Llama a la función remota correctamente y, si tiene éxito, llama a la función javascript original para repoblar el divs.
Aquí está la parte extraña: En FireFox y Chrome, Todo funciona. PERO En IE8 (Beta) esta segunda llamada a la secuencia de comandos Div poblar (que llama a la $.Función getJSON) obtiene datos en caché y no pregunta al servidor!
Espero que esta pregunta tenga sentido: En una cáscara de nuez - ¿Por qué $.getJSON
obtener datos en caché? ¿Y por qué solo afecta a IE8?
7 answers
Solo para hacerle saber, Firefox y Chrome consideran todas las solicitudes Ajax como no-cacheable. IE (todas las versiones) tratan la llamada Ajax como otras solicitudes web. Por eso ves este comportamiento.
Cómo obligar a IE a descargar datos en cada solicitud:
- Como dijiste, usa la opción 'cache' o 'nocache' en jQuery
- Agregue un parámetro aleatorio a la solicitud (feo, pero funciona:))
- En el lado del servidor, establezca la capacidad de caché (por ejemplo, usando un atributo, consulte infra)
Código:
public class NoCacheAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext context)
{
context.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-11-05 09:09:40
Así es como funcionó para mí...
$.ajaxSetup({ cache: false });
$.getJSON("/MyQueryUrl",function(data,item) {
// do stuff with callback data
$.ajaxSetup({ cache: true });
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-26 09:20:03
Gracias Kent por su respuesta. Utilizar $.ajax ('{cache: no}'); funcionó perfectamente. [editar]
O al menos eso pensé. Parece que el jquery $.getJSON no está leyendo ningún cambio realizado en el $.objeto ajax.
La solución que terminó funcionando fue agregar un nuevo parámetro manualmente
var noCache = Date();
$.getJSON("/somepage/someaction", { "noCache": noCache }, Callback);
La resolución de fecha es solo al minuto; lo que efectivamente significa que esta solución todavía se almacena en caché hasta un minuto. Esto es aceptable para mis propósitos.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-11-05 07:28:25
Resolví este mismo problema colocando el siguiente atributo en la Acción en el Controlador:
[OutputCache(Duration = 0, VaryByParam = "None")]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-13 03:49:30
Si está usando ASP.net MVC, considere agregar un método de extensión para implementar fácilmente el almacenamiento en caché como así:
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");
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-05-11 16:55:36
Es posible que deba enviar un interruptor de caché.
Recomendaría usar $.ajax ({cache: no}) por si acaso (añade un sufijo aleatorio a la solicitud get)
(Tiendo a usar $.ajax en todas partes en estos días, más sintonizable)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-11-05 02:51:30
Listo para LA respuesta ?
Http://lestopher.tumblr.com/post/21742012438/if-youre-using-ie8-and-getjson
Por lo tanto, basta con añadir
jQuery.support.cors = true;
Al principio de su guión y BANG it works !
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-29 07:44:31