Stop jQuery .load response from being cached

前端 未结 14 1886
迷失自我
迷失自我 2020-11-22 03:54

I have the following code making a GET request on a URL:

$(\'#searchButton\').click(function() {
    $(\'#inquiry\').load(\'/portal/?f=searchBilling&pid=         


        
相关标签:
14条回答
  • 2020-11-22 04:47

    You have to use a more complex function like $.ajax() if you want to control caching on a per-request basis. Or, if you just want to turn it off for everything, put this at the top of your script:

    $.ajaxSetup ({
        // Disable caching of AJAX responses
        cache: false
    });
    
    0 讨论(0)
  • 2020-11-22 04:49

    Sasha is good idea, i use a mix.

    I create a function

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

    And invoke for diferents parts of my page for example on init:

    Init: function (actionUrl1, actionUrl2, actionUrl3) {

    var ExampleJS= {

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

    ExampleJS.LoadWithoutCache(actionUrl2, "div2"); ExampleJS.LoadWithoutCache(actionUrl3, "div3"); } },

    0 讨论(0)
  • 2020-11-22 04:50

    For PHP, add this line to your script which serves the information you want:

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

    or, add a unique variable to the query string:

    "/portal/?f=searchBilling&x=" + (new Date()).getTime()
    
    0 讨论(0)
  • 2020-11-22 04:52

    If you want to stick with Jquery's .load() method, add something unique to the URL like a JavaScript timestamp. "+new Date().getTime()". Notice I had to add an "&time=" so it does not alter your pid variable.

    $('#searchButton').click(function() {
    $('#inquiry').load('/portal/?f=searchBilling&pid=' + $('#query').val()+'&time='+new Date().getTime());            
    });
    
    0 讨论(0)
  • 2020-11-22 05:00

    This is of particular annoyance in IE. Basically you have to send 'no-cache' HTTP headers back with your response from the server.

    0 讨论(0)
  • 2020-11-22 05:00

    I noticed that if some servers (like Apache2) are not configured to specifically allow or deny any "caching", then the server may by default send a "cached" response, even if you set the HTTP headers to "no-cache". So make sure that your server is not "caching" anything before it sents a response:

    In the case of Apache2 you have to

    1) edit the "disk_cache.conf" file - to disable cache add "CacheDisable /local_files" directive

    2) load mod_cache modules (On Ubuntu "sudo a2enmod cache" and "sudo a2enmod disk_cache")

    3) restart the Apache2 (Ubuntu "sudo service apache2 restart");

    This should do the trick disabling cache on the servers side. Cheers! :)

    0 讨论(0)
提交回复
热议问题