开发者

jQuery.getScript() behaviour

Could someone please explain the behaviour of jQuery's getScript() function?

Consider a javascript file test.js:

var tmp = 'a variable';
alert('here');

When t开发者_JS百科est.js is loaded via html's <script> tag, everything works fine: tmp variable is available in the global scope and a message box appears.

I'm trying to get the similar behavior via this code:

<script>
$(document).ready(function() {
    $.getScript("static/js/proto/test.js");

    setTimeout(function() { 
        // at this point tmp should be available 
        // in the global scope
        alert(tmp); 

    } , 2000); // 2 seconds timeout
}
</script>

But browser's error console reports an "Undefined variable tmp" error. What am I doing wrong? Thank you.


$.getScript may be asynchronous, use the callback parameter:

$.getScript("static/js/proto/test.js", function() {
    // here you are sure that the script has been executed
});

See the documentation for $.getScript: http://api.jquery.com/jQuery.getScript


The real problem with the script was my lack of experience with JS in general and particulary in AJAX: I was trying to run this script on a local machine without a web server.

Guess what: AJAX expects status '200' from a web server to load a document asynchronously. As there was no web server, the status of the async call was '0'.

Thank you everyone for answering.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜