Para jQuery.respuesta de carga de ser almacenado en caché


Tengo el siguiente código haciendo una solicitud GET en una URL:

$('#searchButton').click(function() {
    $('#inquiry').load('/portal/?f=searchBilling&pid=' + $('#query').val());            
});

Pero el resultado devuelto no siempre se refleja. Por ejemplo, hice un cambio en la respuesta que escupía un seguimiento de pila, pero el seguimiento de pila no apareció cuando hice clic en el botón de búsqueda. Miré el código PHP subyacente que controla la respuesta ajax y tenía el código correcto y visitar la página mostró directamente el resultado correcto, pero la salida devuelta por .la carga era vieja.

Si cierro el navegador y volver a abrirlo funciona una vez y luego comienza a devolver la información obsoleta. ¿Puedo controlar esto mediante jQuery o necesito tener mis encabezados de salida de script PHP para controlar el almacenamiento en caché?

Author: dragonmantank, 2008-10-04

14 answers

Debe usar una función más compleja como $.ajax() si desea controlar el almacenamiento en caché por solicitud. O, si solo quieres desactivarlo para todo, pon esto en la parte superior de tu script:

$.ajaxSetup ({
    // Disable caching of AJAX responses
    cache: false
});
 405
Author: John Millikin,
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
2010-11-17 04:00:00

Aquí hay un ejemplo de cómo controlar el almacenamiento en caché por solicitud

$.ajax({
    url: "/YourController",
    cache: false,
    dataType: "html",
    success: function(data) {
        $("#content").html(data);
    }
});
 104
Author: Marshall,
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
2013-08-13 07:13:28

Una forma es agregar un número único al final de la url:

$('#inquiry').load('/portal/?f=searchBilling&pid=' + $('#query').val()+'&uid='+uniqueId());

Donde escribes UniqueID() para devolver algo diferente cada vez que se llama.

 34
Author: Lou Franco,
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-10-03 21:26:09

Otro enfoque para poner la siguiente línea solo cuando se requiera obtener datos del servidor,Agregue la siguiente línea junto con su url ajax.

'?_='+Matemáticas.round (Math.random()*10000)

 7
Author: Gomes,
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-12-19 10:07:48
/**
 * Use this function as jQuery "load" to disable request caching in IE
 * Example: $('selector').loadWithoutCache('url', function(){ //success function callback... });
 **/
$.fn.loadWithoutCache = function (){
 var elem = $(this);
 var func = arguments[1];
 $.ajax({
     url: arguments[0],
     cache: false,
     dataType: "html",
     success: function(data, textStatus, XMLHttpRequest) {
   elem.html(data);
   if(func != undefined){
    func(data, textStatus, XMLHttpRequest);
   }
     }
 });
 return elem;
}
 6
Author: Sasha,
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
2010-06-30 13:07:19

Sasha es buena idea, yo uso una mezcla.

Creo una función

LoadWithoutCache: function (url, source) {
    $.ajax({
        url: url,
        cache: false,
        dataType: "html",
        success: function (data) {
            $("#" + source).html(data);
            return false;
        }
    });
}

E invocar para diferentes partes de mi página por ejemplo en init:

Init: function (actionUrl1, actionUrl2, actionUrl3) {

Var ExampleJS = {

Init: function (actionUrl1, actionUrl2, actionUrl3)           ExampleJS.LoadWithoutCache(actionUrl1, "div1");

ExampleJS.Load Withoutcache (actionUrl2, " div2"); Ejemplos.Load Withoutcache (actionUrl3, " div3"); } },

 5
Author: NGRAUPEN,
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
2011-07-07 19:45:40

Esto es particularmente molesto en IE. Básicamente tienes que enviar encabezados HTTP 'no-cache' de vuelta con tu respuesta del servidor.

 4
Author: Xian,
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-10-03 21:26:15

Para PHP, agregue esta línea a su script que sirve la información que desea:

header("cache-control: no-cache");

O bien, agregue una variable única a la cadena de consulta:

"/portal/?f=searchBilling&x=" + (new Date()).getTime()
 2
Author: nickf,
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-10-04 01:32:11

NO use la marca de tiempo para crear una URL única, ya que cada página que visita se almacena en caché en DOM por jquery mobile y pronto se encontrará con problemas para quedarse sin memoria en los móviles.

$jqm(document).bind('pagebeforeload', function(event, data) {
    var url = data.url;
    var savePageInDOM = true;

    if (url.toLowerCase().indexOf("vacancies") >= 0) {
        savePageInDOM = false;
    }

    $jqm.mobile.cache =  savePageInDOM;
})

Este código se activa antes de cargar la página, puede usar url.indexOf () para determinar si la URL es la que desea almacenar en caché o no y establecer el parámetro de caché en consecuencia.

No utilice window.location=""; para cambiar la URL, de lo contrario, navegará a la dirección y pagebeforeload no lo hará fuego. Para evitar este problema, simplemente use window.ubicación.hash="";

 2
Author: user1545320,
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-23 08:37:00

Puede reemplazar la función de carga de jquery con una versión que tenga caché establecida en false.

(function($) {
  var _load = jQuery.fn.load;
  $.fn.load = function(url, params, callback) {
  if ( typeof url !== "string" && _load ) {
        return _load.apply( this, arguments );
  }
    var selector, type, response,
      self = this,
      off = url.indexOf(" ");

    if (off > -1) {
      selector = stripAndCollapse(url.slice(off));
      url = url.slice(0, off);
    }

    // If it's a function
    if (jQuery.isFunction(params)) {

      // We assume that it's the callback
      callback = params;
      params = undefined;

      // Otherwise, build a param string
    } else if (params && typeof params === "object") {
      type = "POST";
    }

    // If we have elements to modify, make the request
    if (self.length > 0) {
      jQuery.ajax({
        url: url,

        // If "type" variable is undefined, then "GET" method will be used.
        // Make value of this field explicit since
        // user can override it through ajaxSetup method
        type: type || "GET",
        dataType: "html",
        cache: false,
        data: params
      }).done(function(responseText) {

        // Save response for use in complete callback
        response = arguments;

        self.html(selector ?

          // If a selector was specified, locate the right elements in a dummy div
          // Exclude scripts to avoid IE 'Permission Denied' errors
          jQuery("<div>").append(jQuery.parseHTML(responseText)).find(selector) :

          // Otherwise use the full result
          responseText);

        // If the request succeeds, this function gets "data", "status", "jqXHR"
        // but they are ignored because response was set above.
        // If it fails, this function gets "jqXHR", "status", "error"
      }).always(callback && function(jqXHR, status) {
        self.each(function() {
          callback.apply(this, response || [jqXHR.responseText, status, jqXHR]);
        });
      });
    }

    return this;
  }
})(jQuery);

Coloque esto en algún lugar global donde se ejecutará después de que se cargue jquery y debería estar todo listo. Su código de carga existente ya no se almacenará en caché.

 1
Author: Adam Bell,
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
2016-12-05 14:23:44

Prueba esto:

$("#Search_Result").load("AJAX-Search.aspx?q=" + $("#q").val() + "&rnd=" + String((new Date()).getTime()).replace(/\D/gi, ''));

Funciona bien cuando lo usé.

 0
Author: ,
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-11-11 06:30:32

Me di cuenta de que si algunos servidores (como Apache2) no están configurados para permitir o denegar específicamente cualquier "almacenamiento en caché", entonces el servidor puede enviar por defecto una respuesta "en caché", incluso si establece los encabezados HTTP a "no-cache". Así que asegúrese de que su servidor no está "almacenando en caché" nada antes de enviar una respuesta:

En el caso de Apache2 tienes que

1) edite el "disk_cache.conf "file-para deshabilitar la caché add "CacheDisable / local_files" directive

2) cargar módulos mod_cache (En Ubuntu "sudo a2enmod cache" y "sudo a2enmod disk_cache")

3) reinicie el Apache2 (Ubuntu "sudo service apache2 restart");

Esto debería hacer el truco deshabilitando la caché en el lado de los servidores. ¡Salud! :)

 0
Author: techexpert,
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
2011-08-15 04:07:29

Este código puede ayudarte

var sr = $("#Search Result");
sr.load("AJAX-Search.aspx?q=" + $("#q")
.val() + "&rnd=" + String((new Date).getTime())
.replace(/\D/gi, ""));
 0
Author: Ahmad Dwaik 'Warlock',
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
2014-05-29 10:19:13

Si quieres seguir con Jquery .método load (), agrega algo único a la URL como una marca de tiempo JavaScript. "+nueva fecha ().getTime ()". Observe que tuve que agregar un "& time= " para que no altere su variable pid.

$('#searchButton').click(function() {
$('#inquiry').load('/portal/?f=searchBilling&pid=' + $('#query').val()+'&time='+new Date().getTime());            
});
 0
Author: NickStees,
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
2015-09-25 18:57:26