How do I prevent caching Ajax requests in IE 6?

Asked

Viewed 293 times

7

I have the code below, to update a DIV on a page:

var req;

// FUNÇÃO BUSCA ROMANEIOS PARA EXIBIR NA TELA DE MENU.
function buscarRomaneio() {

// Verificando Browser
if(window.XMLHttpRequest) {
   req = new XMLHttpRequest();
}
else if(window.ActiveXObject) {
   req = new ActiveXObject("Microsoft.XMLHTTP");
}

// Arquivo PHP juntamente com o valor digitado no campo (método GET)
var url = "PesquisaRomaneio.php";

// Chamada do método open para processar a requisição
req.open("Get", url, true);

// Quando o objeto recebe o retorno, chamamos a seguinte função;
req.onreadystatechange = function() {

    // Exibe a mensagem "Buscando..." enquanto carrega
    if(req.readyState == 1) {
        document.getElementById('resultado').innerHTML = 'Buscando Romaneios...';
    }

    // Verifica se o Ajax realizou todas as operações corretamente
    if(req.readyState == 4 && req.status == 200) {

    // Resposta retornada pelo PesquisaRomaneio.php
    var resposta = req.responseText;

    // Abaixo colocamos a(s) resposta(s) na div resultado
    document.getElementById('resultado').innerHTML = resposta;
    }
}
req.send(null);
}
setInterval(buscarRomaneio, 60000); //Envia a informação a cada minuto

What happens is the following: In any browser the function works normally. Except in IE6, which will be the exclusive case that I will use (data collector). The function works once and for. I give F5 numerous times and does not change anything. Only changes if I clear the cache or close and open the browser.

Since it is a Windows CE 6, it is all very limited. There is something I can do in this code to solve this problem?

  • 12

    Windows CE 6, IE6, man, if you get the chance, light it on fire!

  • What is the jQuery version you are using?

  • 5

    If you’re working at a company where the director insists on using IE6, then it’s past time for you to send your resume around and do some interviews.

  • The problem was the collectors bought... the value was high and all came in this configuration. I’m working on the code and as I change it the data fades/appears.....

  • @Guilhermenascimento aberta.

  • Who has denied, can you tell me what I can improve? The doubt is valid, I did not understand why the -1

  • @Diego I did not deny, but I suppose it is because in the title and tag speaks jquery and in the code there is nothing about jQuery. I will edit and give you +1

  • @Guilhermenascimento, it was bad. The pressure here is great and I lost myself in terms. Sorry. And thanks for the answer, solved the problem :)

Show 3 more comments

1 answer

8


This cache problem even occurred in Internet Explorer more modern (when using Activex) and sometimes occurs in other situations, varying as the result of the back-end.

The practical solutions are:

  1. Adjust the server cache in your PHP:

    Edit the PesquisaRomaneio.php and add that at the top, should come first of all:

    <?php
    $g = gmdate('D, d M Y H:i:s');
    header('Expires: ' . $g . ' GMT');
    header('Last-Modified: ' . $g . ' GMT');
    header('Cache-Control: no-store, no-cache, must-revalidate');
    header('Cache-Control: post-check=0, pre-check=0', false);
    header('Pragma: no-cache');
    
    //Código restante abaixo
    
  2. Add a query string suffix to avoid caching. This is the same technique jQuery uses for when you add cache: false. Do so:

    // Arquivo PHP juntamente com o valor digitado no campo (método GET).
    var url = "PesquisaRomaneio.php";
    
    // Adiciona ? se não tiver query string. Caso contrário adiciona &.
    url += url.indexOf("?") === -1 ? "?" : "&";
    
    // Adiciona o sufixo para evitar cache.
    url += "_=" + (new Date().getTime());
    
    // Chamada do método open para processar a requisição.
    req.open("GET", url, true);
    

Tip

I recommend changing the setInterval for setTimeout. That’s because the setInterval does not wait, which can cause simultaneous requests causing side effects. See some answers on the subject:

So you could change the code to something like:

function buscarRomaneio() {

    // Verificando Browser
    if (window.XMLHttpRequest) {
       req = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
       req = new ActiveXObject("Microsoft.XMLHTTP");
    }

    // Ajusta os segundos
    var segundos = 60;

    // Arquivo PHP juntamente com o valor digitado no campo (método GET).
    var url = "PesquisaRomaneio.php";

    // Adiciona ? se não tiver query string. Caso contrário adiciona &.
    url += url.indexOf("?") === -1 ? "?" : "&";

    // Adiciona o sufixo para evitar cache.
    url += "_=" + (new Date().getTime());

    // Chamada do método open para processar a requisição.
    req.open("GET", url, true);

    document.getElementById('resultado').innerHTML = 'Buscando Romaneios...';

    req.onreadystatechange = function() {

        // Verifica se o Ajax realizou todas as operações corretamente
        if (req.readyState == 4) {
            if (req.status == 200) {
                // Resposta retornada pelo PesquisaRomaneio.php
                var resposta = req.responseText;

                // Abaixo colocamos a(s) resposta(s) na div resultado.
                document.getElementById('resultado').innerHTML = resposta;
            } else {
                document.getElementById('resultado').innerHTML = "Erro: " + req.status;
            }

            setTimeout(buscarRomaneio, segundos * 1000);
        }
    };

    req.send(null);
}

// Inicia a função
buscarRomaneio();

This will do the shooting without needing to wait 60 seconds the first time. However, if you want this wait then switch to:

    req.send(null);
}

// Inicia a função.
setTimeout(buscarRomaneio, 60000);
  • Thank you William, I used the second option and it worked! Thank you very much!

  • 1

    @Diego added a suggestion in the reply

  • 1

    Great tip, I’ll change it. Thank you!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.