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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

it is still not working, and keep saying turnLongURL is not defined... does it make any difference if i am editing a greasemonkey script?
@Quentin What is the best way to account for jsonp race conditions?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.