Prevent browser from caching AJAX requests

前端 未结 4 753
小鲜肉
小鲜肉 2020-12-08 04:52

I\'ve setup an app and it works fantastic on Opera and Firefox, but on Google Chrome it caches the AJAX request and will give stale data!

http://gapps.qk.com.au is t

相关标签:
4条回答
  • 2020-12-08 05:27

    The browser cache behaves differently on different settings. You should not depend on user settings or the user's browser. It's possible to make the browser ignore headers also.

    There are two ways to prevent caching.

    --> Change AJAX request to POST. Browsers don't cache POST requests.

    --> Better Way & good way: add an additional parameter to your request with either the current time stamp or any other unique number.

    params = "action=" + action 
             + "&domain=" + encodeURIComponent(domain) 
             + "&preventCache="+new Date();
    
    0 讨论(0)
  • 2020-12-08 05:31

    Another alternative to the Javascript solution is to use custom headers: In PHP it would look like this:

    <?php
       header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");//Dont cache
       header("Pragma: no-cache");//Dont cache
       header("Expires: Thu, 19 Nov 1981 08:52:00 GMT");//Make sure it expired in the past (this can be overkill)
    ?>
    
    0 讨论(0)
  • 2020-12-08 05:39

    Below line of code worked for me.

    $.ajaxSetup({ cache: false });
    
    0 讨论(0)
  • 2020-12-08 05:51

    I was using jQuery ajax request when I ran into this problem.

    According to jQuery API adding "cache: false" adds a timestamp like explained in the accepted answer:

    This only works with GET and HEAD requests though but if you're using POST the browser doesn't cache your ajax request anyways. There's a but for IE8, check it out in the link if needed.

    $.ajax({ 
    type: "GET",
    cache: false, 
    });
    
    0 讨论(0)
提交回复
热议问题