views:

1752

answers:

4

I'm trying to load an external JavaScript using jQuery's getScript(), like this:

$.getScript("http://api.recaptcha.net/js/recaptcha_ajax.js", function(data) {
 window.alert(data);
});

but as the alert window shows, the data variable in the callback function is undefined, unlike promised in http://docs.jquery.com/Ajax/jQuery.getScript#urlcallback.

Anyone know why this might be?

Thanks.

+1  A: 

Yes it is loading the script but strangely the data variable is undefined. But i tried accessing the variable (RecaptchaStr_en) from the script from remote site and it is defined.

$.getScript("http://api.recaptcha.net/js/recaptcha_ajax.js", function(data) {
        window.alert(data);
        alert($(RecaptchaStr_en));
    });
TheVillageIdiot
+1  A: 

If you look at the source to getScript (line 3338 in jQuery-1.3.2.js), you can see that the documentation is wrong here. The data parameter is for sending data to the server in the query string, which jQuery assumes you won't need for loading scripts; it's used in, for instance, getJSON. getScript just hardcodes data to null, and automatically evaluates the retrieved script for you.

So the bad news is that the documentation is wrong. The good news is that you probably just wanted to evaluate the script anyway, so you probably don't even need the callback at all.

C Pirate
A: 

Just load your scripts with relative paths i.e. /Script/MyScript.js rhather than http://mywebsite.com/Script/MyScript.js

For C Pirate, there is nothing wrong about documentation, that works as expected. XMLHttpRequest doesn't allow cross-domain requests, and seems that the data parameter is undefined even if you put the whole path into your same domain.

DotNetWise
A: 

When you define the dataType to be script the request is not made using XMLHttpRequest but rather the tag, so the data and success objects in the callback are not available.

Al