Javascript 如何通过ajax调用从另一个目录同步加载脚本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4539740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:50:56  来源:igfitidea点击:

How do you synchronously load a script from another directory via an ajax call?

javascriptjqueryajax

提问by Alex

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

我经常需要通过ajax加载其他javascript文件,所以一开始我使用了jQuery提供的标准函数来加载脚本:

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

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:

但这不起作用,因为 $.getScript 是异步的($.ajax 的 jQuery API 说默认情况下“async”设置为 true;该主题在 $.getScript 的 API 的评论中讨论:http:/ /api.jquery.com/jQuery.getScript/)。所以我写了这个函数,正如某人在上面链接的 API 页面的评论中提供的那样:

load:function(script,callback){

    jQuery.ajax({

        async:false,

        type:'GET',

        url:script,

        data:null,

        success:callback,

        dataType:'script'

    });

},

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.

这似乎工作得很好,所以我继续,但我最近注意到,这仅适用于同一目录中的脚本,例如。调用 myObj.load('test.js') 效果很好,但调用 myObj.load('test/test.js') 根本不起作用。

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

感觉好像我遗漏了一些明显的东西,但我没能找到问题所在。任何的想法?

采纳答案by T.J. Crowder

Update: See the comment stream below, it's nothing to do with jQuery, it's a file permissions problem on the server.

更新:见下面的评论流,与jQuery无关,这是服务器上的文件权限问题。



Original answer:

原答案

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.

您是否从浏览器收到任何错误?例如,在 Chrome 或 Safari 中,如果您打开开发工具并查看控制台选项卡,是否显示错误?或者在 Firefox 中,安装 Firebug 并检查 Firebug 的控制台。或者在 IE 中,使用免费版本的 VS.Net... 应该有什么东西向你抱怨。

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

您还可以通过提供error函数而不是假设成功来从代码本身获取更多信息:

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.
    }
});

Update: You've said you see textStatus= 'error' and errorThrown= undefined. Very strange. Does the samescript 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.

更新:你说过你看到textStatus= 'error' 和errorThrown= undefined。很奇怪。如果您移动它以使其不在子路径上,相同的脚本是否有效?我想知道子路径是否是一个红鲱鱼,真正的问题是脚本中的语法错误。



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

题外话真的一定要同步吗?你不能只轮询一个符号出现吗?只是同步 ajax 请求确实破坏了用户体验。在许多浏览器中,不仅您自己的页面而且所有页面在请求期间都会锁定。

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

这就是轮询的意思:假设我想从 JavaScript 异步加载 jQuery:

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);
        }
    }
}

Usage:

用法:

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

回答by Benny Neugebauer

You can set ajax calls to be synchronous by default using ajaxSetup. This is how it looks like:

默认情况下,您可以使用ajaxSetup将 ajax 调用设置为同步。这是它的样子:

$.ajaxSetup({async:false});
$.getScript('script_name.js', callback_function);

If you need asynchronous calls again, just enable it with:

如果您再次需要异步调用,只需启用它:

$.ajaxSetup({async:true});