5

我正在尝试从一些代码主机导入一些 javascript 文件。

    $.when(
        $.getScript('http://pingzi.googlecode.com/svn-history/r30/branches/wangqi/web/jquery.window.min.js'),
        $.getScript('http://mottie.github.com/tablesorter/js/jquery.tablesorter.js'),
        $.getScript('http://tconnell.com/samples/scroller/lib/jquery.tablesorter.scroller.js'),
        $.getScript('http://code.highcharts.com/stock/highstock.js'), 
        $.Deferred(
            function(deferred) { 
                $(deferred.resolve);
            }
        )
    ).done(function() {  
       // my function goes here....
    });

当我尝试调用这些 URL 来导入 js 文件时,URL 会附加?_=1344036242417,然后我实际上无法访问我想要的脚本文件。

IE "NetworkError: 404 Not Found - http://pingzi.googlecode.com/svn-history/r30/branches/wangqi/web/jquery.window.min.js?_=1344036242417"

任何人都知道如何绕过这个问题?先感谢您。

4

4 回答 4

7

That's because caching in ajax is turned off by default in jQuery, to turn it on and remove the querystring do :

$.ajaxSetup({ 
    cache: true 
}); 

but that could also affect other ajax calls that you don't want to cache, there's a lot more on this in the docs for getScript, and there's even a little how-to on creating a cached getScript function called cachedScript.

You can also enable caching in $.getScript by redefining the function with a new option to turn the cache on/off by passing true or false :

$.getScript = function(url, callback, cache){
    $.ajax({
            type: "GET",
            url: url,
            success: callback,
            dataType: "script",
            cache: cache
    });
};
于 2012-08-03T23:48:13.487 回答
5

jQuery对此类查询具有自动缓存机制。如果您不希望添加额外的参数,请使用以下设置:

$.ajaxSetup({
  cache: true
});

来源:http ://api.jquery.com/jQuery.getScript/#caching-requests

于 2012-08-03T23:33:09.730 回答
4

jQuery 会自动添加_=1344036242417,这会破坏 URL。笔记:

为了防止 jQuery 添加该参数:Ajax get request with useless parameter。总结这个答案,$.ajaxSetup在调用$.getScript()set之前使用cache: true

是[原文如此] 默认值,$.getScript()将缓存设置设置为false. 这会将时间戳查询参数附加到请求 URL,以确保浏览器在每次请求时下载脚本。您可以通过使用全局设置缓存属性来覆盖此功能$.ajaxSetup()

$.ajaxSetup({
    cache: true
});
于 2012-08-03T23:31:33.587 回答
2

附加的查询字符串是为了防止缓存。您可以通过启用缓存来禁用此功能:

$.ajaxSetup({
  cache: true
});
于 2012-08-03T23:30:38.047 回答