Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

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

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

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'

    });

},

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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

$.ajaxSetup({async:true});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...