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++;
}

猜你喜欢

转载自www.cnblogs.com/sea-breeze/p/10232081.html