How to prevent caching from jQuery Ajax?

后端 未结 3 1197
生来不讨喜
生来不讨喜 2020-12-21 08:50

Could anyone please help me with this? I have a web page using .manifest for offline storage caching. In that page, I use jQuery ajax call to get the data from the server. I

相关标签:
3条回答
  • 2020-12-21 09:00

    put the random string into url like "get.php?random="+Math.random()" can solve this problem. It is not the best solution but It works great.

    0 讨论(0)
  • 2020-12-21 09:01

    I have this piece of code at the top of each page/Master page

        //Disable caching in IE, becuase it's EVIL!
        $(document).ready(function () {
            $.ajaxSetup({ cache: false });
        });
    
    0 讨论(0)
  • 2020-12-21 09:10

    I know I'm very very late to this party but just to put it out there. And I'm sorry to resurrect this question from Zombie land. In safari and some older browsers, (from what I've experienced till now, cache:false doesn't seem to work sometimes). for a more cross browser compatible solution, you could add a data option to the ajax() call and add a random number generator as a parameter. It would be something like this.

     var callback = function () {
       $.ajax({
          type: "GET",
          url: requestUrl,
          success: localSuccess,
          error: error,
          dataType: "text",
    
          //won't work sometimes
          cache:false,
    
          //start random number generator
          data : { r: Math.random() }
         //end random number generator
       });
      }
    

    This way, everytime a server call happens, a new random number will be generated, and since the data is different from the previous requests, ajax requests wont be cached and will ensure a fresh server call every single time. And in your server, you could ignore this variable r.

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