jQuery禁止Ajax請求緩存


 

一 現象

 

get請求在有些瀏覽器中會緩存。瀏覽器不會發送請求,而是使用上次請求獲取到的結果。

post請求不會緩存。每次都會發送請求。

 

二 解決 

 

jQuery提供了禁止Ajax請求緩存的方法:

$.ajax({
    type: "get",
    url: "http://www.baidu.com?_=",
    cache: false
});

它的工作原理是在GET請求參數中附加時間戳"_={timestamp}"

 

三 源碼

 

jQuery.extend( {
    now: function() { // 獲取毫秒數
        return +( new Date() );
    }
} );

var nonce = jQuery.now(); // 加載jQuery腳本文件時,獲取時間戳。使用時每次加一。

var rquery = ( /\?/ ); // 檢測問號

var rts = /([?&])_=[^&]*/; // 檢測下划線參數

// Add anti-cache in url if needed
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++;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM