jQuery有三种不同的缓存选项。默认值null允许所有请求进行缓存,但脚本和JSON请求除外,而true和false适用于所有请求。据我所知,在load()方法中无法提供选项参数,因此您需要更改全局jQuery ajax选项。
以下是我提供的不同方法:
第一种方法尝试在请求完成后保留先前的全局选项(但存在其缺点)。
第二种方法忽略默认设置,并仅设置选项,以便您始终允许使用缓存来处理ajax结果(如果这对您不是问题,我建议您选择这个,因为它是最简单的,没有隐藏的陷阱),并且
第三个示例是如果您想允许脚本的缓存,但不允许其他ajax请求。
示例1:
我的第一个示例展示了如何在load()请求后恢复正常设置:
//first store defaults (we may want to revert to them)
1: var prevCacheVal = $.ajaxSettings.cache;
//then tell jQuery that you want ajax to use cache if possible
2: $.ajaxSetup({cache: true});
//then call the load method with a callback function
3: $(myDiv).load(myURL,function(){
/* revert back to previous settings. Note that jQuery makes
a distinction between false and null (null means never
cache scripts, false means never cache anything). so it's
important that the triple-equals operators are used, to
check for "false" and not just "falsey" */
4: if (prevCacheVal === false) $.ajaxSetup({cache: false})
5: else if (prevCacheVal !== true) $.ajaxSetup({cache: null});
//else prev was true, so we need not change anything
6: });
重要提示:在进行上述操作时,需要小心确保每次只发送一个请求,因为每次存储和切换“默认”可能会导致竞争条件。如果您需要上述功能以及能够发送并行请求的能力,则最好编写自己的jQuery.ajax()方法包装器,以便您可以按照每个请求的基础传递cache选项。这类似于Andres下面建议的方法,但是使用了我建议的修复程序来指定cache: true并使用jQuery.html();而不是innerHTML。但是,情况比这更加复杂,因为内部jQuery.html();使用全局选项请求脚本,因此您还需要覆盖一些深入函数调用内部的内部功能,html();使 - 不要轻率地做出这样的事情,但肯定是可能的。
示例2:(推荐给原问题提问者)
现在,如果您不关心恢复默认值,并且希望缓存对于所有ajax请求都打开,那么您可以简单地调用$.ajaxSetup({cache: true});并像以前一样调用load():
$.ajaxSetup({cache: true});
$(myDiv).load(myURL);
示例3:
如果你不想从缓存中加载myURL(例如,它是动态的),但是又希望缓存脚本,那么你需要在myURL中添加一个独特或随机查询参数,如:
$.ajaxSetup({cache: true});
$(myDiv).load(myURL + "?myuniquetime=" + Date.getTime());
/* getTime() is milliseconds since 1970 - should be unique enough,
unless you are firing of many per second, in which case you could
use Math.random() instead. Also note that if myURL already includes
a URL querystring, you'd want to replace '?' with '&' */