How does jQuery disable AJAX caching?

2019-09-15 23:07发布

To disable caching files from ajax requests, you can use jQuery's

$.ajaxSetup({
    cache: false
});

But how does jQuery do this? I know jQuery is a javascript library, so whatever can be done with jQuery can be done with plain javascript. So my question is: What is the javascript code that jQuery uses under the hood to turn off ajax file caching?

4条回答
唯我独甜
2楼-- · 2019-09-15 23:39

The easiest way to shut off browser caching of Ajax requests is with a query string parameter based on time.

var t = new Date().getTime();

console.log('some-url?_='+t);

This yields the following query string

?_=1481683928873

The browser will see this as a different request (assuming it only makes one per microsecond) and it will request the content from the server, rather then serving it from its cache.

查看更多
来,给爷笑一个
3楼-- · 2019-09-15 23:52

I think that Today's Browsers use onunload = function(){} just like that (yes, exactly) to prevent the Browser from caching a web page, as it was when you left it to go to another page.

It's important to under stand, however, that that is not the same as the Browser's ability to remember the JavaScript loaded from your <script type='text/javascript' src='somePage.js'></script> tags when they have that src attribute. If you change your JavaScript on a live site, you'll want to change the name of that file, or, if the Client has not cleared their cache their Browser will attempt to load the file as it remembers it.

查看更多
一夜七次
4楼-- · 2019-09-15 23:53

This is the source of the cache

        if ( s.cache === false ) {
            s.url = rts.test( cacheURL ) ?

                // If there is already a '_' parameter, set its value
                cacheURL.replace( rts, "$1_=" + nonce++ ) :

                // Otherwise add one to the end
                cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
        }

s is ajax's option, If you set cache false, It will add a search to you request url, The 'nonce' is jQuery.now(), It's a time; So browser will not user cache when you send ajax , request url always differenrt.

查看更多
一夜七次
5楼-- · 2019-09-15 23:53

If you read the docs they say:

cache (default: true, false for dataType 'script' and 'jsonp')
Type: Boolean

If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET.

查看更多
登录 后发表回答