jQuery 如何让 Ajax 不请求缓存? 如何禁止 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++;
- }
更多前端开发 https://www.html.cn/ 知识, 请查阅 HTML 中文网 !!
来源: http://www.css88.com/qa/jquery/17084.html