为什么jQuery的ajax会自动运行脚本?

时间:2013-11-09 04:16:26

标签: javascript jquery ajax iframe jquery-plugins

我最近注意到,如果在将jQuery注入内部iframe后立即调用jQuery ajax,jQuery将失去其功能 - 如jQuery(..)。dialog(),。draggable和任何其他插件。如果ajax调用被注释掉,jQuery工作正常。这是一个已知的错误,或者我做错了什么?这个问题可以在这个文件中看到,jQuery位于同一个目录中:

<html>
<head>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
    <script src="jquery.js"></script>
    <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
</head>
<body>

Try and <button id="btn">load</button>
<iframe width=300 height=300></iframe>

<script>
"use strict";
jQuery('#btn').click(function(){
    var $ = jQuery;
    console.log(typeof jQuery('iframe').dialog);
    var doc = jQuery('iframe')[0].contentDocument;
    function insertscript(src) {
        var newscript = doc.createElement('script');
        newscript.setAttribute('src',src);
        doc.documentElement.appendChild(newscript);
    }
    insertscript('jquery.js');

    //This breaks the jQuery plugins:
    var test = $.get('jquery.js',function(){
        //Now we know jQuery should be in the frame.
    });

    //So does this:
    //jQuery.ajax({url:'http://192.168.1.17/wordpress/wp-includes/js/jquery/jquery.js',cache:true,processData:false});

    console.log(typeof jQuery('iframe').dialog);
    window.setTimeout(function(){
        //jQuery is no longer the original jQuery object. Note the cached reference $().dialog does exist though.
        console.log('after awhile... dialog is ' + typeof jQuery('iframe').dialog);
    },3000)
    //jQuery.ajax({url:jqurl,cache:true,processData:false});
});
</script>
</body></html>

这是问题的最小示例,确保iframe已经加载了某个jQuery.js(然后ajax应该有缓存的脚本),然后将其他一些内容添加到iframe中。

单击“加载”,之后,控制台日志将显示“一段时间后...对话框未定义” - 仅在使用ajax时。

更新:看起来$.get('jquery.js')实际上运行了脚本。当alert.js具有警报功能时,$.get('alert.js')会显示警报。 (在jQuery的情况下,重新定义全局jQuery引用。)为什么jQuery的ajax有这种行为?所有ajax实现都会发生这种情况吗?

1 个答案:

答案 0 :(得分:0)

如前所述有人回答(其答案已删除?),jQuery ajax会根据您请求的内容类型自动选择要执行的操作。 (遗憾的是,记录不足的特征)。加载外部js不仅会在浏览器获取脚本时返回,还会运行脚本。

每当你稍后重新包含jQuery时,它会重写window.jQuery对象,因此删除了jQuery.prototype.dialog等。

Firefox .watch功能可以在这种情况下提供帮助,以查看重新定义的内容。例如,这将为您提供重新定义jQuery的任何内容的堆栈跟踪:

window.watch('jQuery',function() { console.trace() } )
相关问题