How does jQuery disable AJAX caching?

岁酱吖の 提交于 2019-12-25 04:24:53

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/41133752/how-does-jquery-disable-ajax-caching

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!