你如何同步通过Ajax调用加载从另一个目录中的脚本? [英] How do you synchronously load a script from another directory via an ajax call?

查看:131
本文介绍了你如何同步通过Ajax调用加载从另一个目录中的脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常需要通过AJAX加载其他JavaScript文件,所以一开始我使用的标准功能,jQuery提供了脚本加载:

I often need to load other javascript files via ajax, so at the beginning I used the standard function jQuery provides for script loading:

$.getScript('script_name.js',callback_function());

但是,这并没有奏效,因为$ .getScript是异步的(为$阿贾克斯jQuery的API称异步设置为默认值是true;主题为$ .getScript API的意见进行讨论: http://api.jquery.com/jQuery.getScript/ )。所以我写了这个功能,在API页面上面链接中发表了被人:

But this didn't work out, since $.getScript is asynchronous (the jQuery API for $.ajax says 'async' is set to true by default; topic is discussed in the comments of the API for $.getScript: http://api.jquery.com/jQuery.getScript/). So I wrote this function, as provided by someone in the comments of the API page linked above:

load:function(script,callback){

    jQuery.ajax({

        async:false,

        type:'GET',

        url:script,

        data:null,

        success:callback,

        dataType:'script'

    });

},

这看来效果不错,让我去,但我最近注意到,这仅适用于在同一目录,如脚本。调用myObj.load('test.js)效果很好,但调用myObj.load(测试/ test.js')不会在所有的工作。

This seemed to work well, so I went on, but I recently noticed, that this only works for scripts in the same directory, eg. calling myObj.load('test.js') works well, but calling myObj.load('test/test.js') doesn't work at all.

这感觉就像我失去了一些东西很明显,但我没能发现问题。你知道吗?

It feels like I'm missing something obvious, but I didn't manage to find the problem. Any idea?

推荐答案

更新:请参阅下面的注释流,这是没有任何关系的jQuery,它的服务器上的文件权限问题

原来的答复

你得到从浏览器的任何错误?例如,在Chrome或Safari浏览器,如果你打开​​了开发工具,并期待在控制台选项卡,它显示错误?或者在Firefox中安装的Firebug并为您在Firebug的控制台。或者在IE中,使用VS.Net ...一些应该被抱怨你的东西的免费版本。

Do you get any errors from the browser? For instance, in Chrome or Safari, if you open the Dev Tools and look at the Console tab, does it show errors? Or in Firefox, install Firebug and check in Firebug's console. Or in IE, use the free version of VS.Net... Something should be complaining to you about something.

您还可以得到更多的信息,从code本身通过提供一个错误函数,而不是假设的成功:

You can also get more information from your code itself by supplying an error function rather than assuming success:

jQuery.ajax({
    async:false,
    type:'GET',
    url:script,
    data:null,
    success:callback,
    dataType:'script',
    error: function(xhr, textStatus, errorThrown) {
        // Look at the `textStatus` and/or `errorThrown` properties.
    }
});

更新:你说你看到 textStatus ='错误'和 errorThrown =不确定。很奇怪。是否在同一个脚本工作,如果你移动它,所以它不是一个子路径?我不知道该子路径是一个红色的鲱鱼,而真正的问题是在脚本中的语法错误。

Update: You've said you see textStatus = 'error' and errorThrown = undefined. Very strange. Does the same script work if you move it so it's not on a subpath? I wonder if the subpath is a red herring, and the real problem is a syntax error in the script.

题外话:它的真正的必须是同步?你不能只是轮询出现一个符号?这只是同步Ajax请求的真的垃圾的用户体验。在很多浏览器,不只是你自己的页面,但所有页面的请求过程中锁定。

Off-topic: Does it really have to be synchronous? You can't just poll for a symbol to appear? It's just that synchronous ajax requests really trash the user experience. In many browsers, not just your own page but all pages lock up during the request.

这就是我所说的投票:假设我要加载的jQuery异步JavaScript中:

Here's what I mean by polling: Suppose I wanted to load jQuery asynchronously from JavaScript:

function loadScript(url, symbol, callback) {
    var script, expire;

    // Already there?
    if (window[symbol]) {
        setTimeout(function() {
            callback('already loaded');
        }, 0);
    }

    // Determine when to give up
    expire = new Date().getTime() + 20000; // 20 seconds

    // Load the script
    script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    document.body.appendChild(script);

    // Start looking for the symbol to appear, yielding as
    // briefly as the browser will let us.
    setTimeout(lookForSymbol, 0);

    // Our symbol-checking function
    function lookForSymbol() {
        if (window[symbol]) {
            // There's the symbol, we're done
            callback('success');
        }
        else if (new Date().getTime() > expire) {
            // Timed out, tell the callback
            callback('timeout');
        }
        else {
            // Schedule the next check
            setTimeout(lookForSymbol, 100);
        }
    }
}

用法:

// Load jQuery:
loadScript("path/to/jquery.min.js", "jQuery", function(result) {
    // Look at 'result'
});

这篇关于你如何同步通过Ajax调用加载从另一个目录中的脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆