Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...