jQuery版本1.5 - ajax - <script>标记时间戳问题

Nor*_*mas 13 javascript ajax jquery timestamp jquery-1.5

如果我使用带有脚本标记的ajax(jQuery)加载一些内容,jQuery 1.5会将时间戳添加到脚本标记src url中.见下面的例子.

示例:我用ajax加载的内容:

<div>text1</div>
<script type="text/javascript" src="/js/abc-xyz.js?r=1.1"></script>
Run Code Online (Sandbox Code Playgroud)

这是我将以前的内容插入页面后加载脚本代码的src网址:

.../js/abc-xyz.js?r=1.1&_=1297892228466
Run Code Online (Sandbox Code Playgroud)

有人知道为什么会这样吗?它只发生在jQuery 1.5上.jQuery 1.4.4不会发生这种情况.

代码示例:

$.ajax({
    url: content.html,
    type: 'GET',
    data: someDataObject,
    success: function(data) {
        // some code here

    },
    error: function(data) {
        // some code here
    }
});
Run Code Online (Sandbox Code Playgroud)

谢谢.

Nor*_*mas 9

请参阅我从jQuery团队得到的答案.机票#8298:http://bugs.jquery.com/ticket/8298

回答:

在检查您的报告和您的代码示例后,我得出结论,这不是一个错误.我也做了这个测试用例 jQuery 1.4+(直到1.5)有一个错误导致缓存选项不对脚本请求默认为false.这个错误(见#7578)已在1.5中修复.现在您可能知道或不知道的是,jQuery在执行DOM操作时会执行特殊处理脚本标记(以防止IE中的某些错误).它过滤掉它们并通过ajax请求它们.这解释了为什么即使是"普通"内联脚本标记突然被请求使用其他url参数.如果它有不必要的副作用,有办法解决这个问题.

  1. 使用$.ajaxSetup({ cache: true })适当的时候

  2. 使用 prefilter进行脚本请求,例如检查你不希望添加random参数的url,并在prefilter中为那些设置cache:true

  3. 例如,成功回调处理脚本标记自己做这些事情..

..lines:

var elems = $(htmlwithscripttags);
elems.filter("script") //now do whatever with the scripts
elems.filter(":not(script)").appendTo("body"); //e.g.
Run Code Online (Sandbox Code Playgroud)

  • `2` 对我来说效果很好:`$.ajaxPrefilter('script', function(options) { options.cache = true; });` (2认同)

Sha*_*haz 7

Michael 的评论是正确的,如果你想禁用它,请cache: true在ajax请求中使用: .要启用,请使用cache: false(我认为是默认设置).

要禁用时间戳:

$.ajax({
    url: content.html,
    cache: true,
    type: 'GET',
    data: someDataObject,
    success: function(data) {
        // some code here

    },
    error: function(data) {
        // some code here
    }
});
Run Code Online (Sandbox Code Playgroud)