Ya Zhuang
Ya Zhuang

Reputation: 4660

javascript JSONP callback function not defined

(
function restoreURL() {
    function turnLongURL(data) {
        window.location = data.url;
    }

    var shortUrl = window.location.href;

    var url = "http://json-longurl.appspot.com/?url=" + shortUrl + "&callback=turnLongURL";

    var script = document.createElement('script');
    script.setAttribute('src', url);

    document.getElementsByTagName('head')[0].appendChild(script); 
})();

code is above, but the firebug told me, turnLongURL is not defined

why is that?

Upvotes: 3

Views: 5017

Answers (1)

Quentin
Quentin

Reputation: 944441

JSON-P is added to the document using a script element, so the function call inside it has to reference a function that exists in the global scope.

turnLongURL is limited to the scope of restoreURL since it is defined inside it.

Moving the function declaration to the global scope, or changing it to a function statement thus:

window.turnLongURL = function (data) {

… should make it work.

Remember to account for the possibility of race conditions should multiple JSON-P requests be sent out before the first returns.

Upvotes: 8

Related Questions