jQuery Ajax错误 [英] jquery ajax bug
问题描述
我有以下HTML页面:
I have the following HTML page:
sample_page.html:
<h1>sample html page</h1>
<script type="text/javascript" src="sample_page.js"/>
sample_page.js
是一个空的JSfile.
The sample_page.js
is an empty JSfile.
现在尝试使用JQuery AJAX加载它:
Now try to load it using JQuery AJAX:
$('div').load('sample_page.html', function(){
alert('loaded');
});
现在,如果您使用Firebug来检查请求,您将看到jQuery请求sample_page.html
并且页面本身被缓存了(http状态代码304).但是,它会从HTML文件中剥离脚本标签并执行它们(可能使用$.getScript
).问题在于,它将时间戳附加到JavaScript文件,因此从不对其进行缓存(状态200).
Now if you use Firebug to examine the request, you'll see that jQuery requests the sample_page.html
and the page itself gets cached (http status code 304). However, it strips out the script tags from the HTML file and executes them (probably using $.getScript
). The problem is that it appends a time-stamp to the JavaScript file so it is never cached (status 200).
对于单页面应用程序,这意味着用户每次访问页面时,都会重新加载脚本文件.反正有解决此问题的方法吗?
For a single paged application, this means that every-time a user goes to a page, the script file is reloaded again. Is there anyway to fix this issue?
推荐答案
Apparently, .getScript()
does not support the any caching options. Its source code is this:
getScript: function( url, callback ) {
return jQuery.get(url, null, callback, "script");
}
由于它是.get()
周围的便利包装,因此您可以:
Since it is a convenience wrapper around .get()
you could:
-
要么通过
.ajaxSetup()
修改全局Ajax选项,然后再调用.load()
.这些设置也会影响.getScript()
:
either modify the global Ajax options via
.ajaxSetup()
before you call.load()
. These settings would also affect.getScript()
:
$.ajaxSetup({ cache: true });
,或者您可以修改getScript()
本身:
$.getScript = function(url, callback){
$.ajax({
type: "GET",
url: url,
success: callback,
dataType: "script",
cache: true
});
};
jQuery不会脱离此修改.除了默认情况下启用缓存外,此代码在所有目的和用途上都完全等同于原始实现.
jQuery will not break from this modification. This code is absolutely equivalent to the original implementation for all intents and purposes, except that caching is enabled by default.
这篇关于jQuery Ajax错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!