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 above but firebug told me turnLongURL not defined

why?

+3
source share
1 answer

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

turnLongURLlimited to the area restoreURL, as it is defined inside it.

Moving a function declaration to a global scope or changing it to a function statement in this way:

window.turnLongURL = function (data) {

... should make it work.

Do not forget to consider the race conditions if several JSON-P requests must be sent before the first return.

+8

Source: https://habr.com/ru/post/1782023/


All Articles