简体   繁体   中英

JSONP Script Callback Not Working

I want to execute a callback once I load a script using pure javascript. I am able to load the script correctly, but my callback is not firing. I heard using JSONP I can do this type of stuff, however, I cannot quite get it to work. Here is my code:

function foo(){
   alert('got the data');
}

var el = document.createElement("script");
el.setAttribute("src", "//ajax.googleapis.com/ajax/libs/webfont/1.5.0/webfont.js?callback=foo");
document.body.appendChild(el);

JSONP has nothing to with that. The URL you are trying to load already returns JavaScript, so you need to do is bind a load event handler to the element:

var el = document.createElement("script");
el.setAttribute("src", "//ajax.googleapis.com/ajax/libs/webfont/1.5.0/webfont.js");
el.onload = function() {
    // script loaded
};
document.body.appendChild(el);

See also How do I include a JavaScript file in another JavaScript file?


JSONP is used as an alternative to Ajax when you want to load data from an external domain, but it is something the server has to support. If the server supports it, instead of returning (for example) simple JSON:

{"foo": 42}

it would wrap it in callbackName(...); to create a JS script with a single function call:

callbackName({"foo": 42});

The actual function name is taken from the GET parameter callback .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM