3
(
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?

Ya Zhuang
  • 4,652
  • 31
  • 40

1 Answers1

8

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335