简体   繁体   English

JSONP脚本回调不起作用

[英]JSONP Script Callback Not Working

I want to execute a callback once I load a script using pure javascript. 我想在使用纯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. 我听说使用JSONP可以做到这类事情,但是我不能完全使它起作用。 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. JSONP与此无关。 The URL you are trying to load already returns JavaScript, so you need to do is bind a load event handler to the element: 您尝试加载的URL 已经返回了JavaScript,因此您需要做的是将加载事件处理程序绑定到元素:

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? 另请参阅如何在另一个JavaScript文件中包含一个JavaScript文件?


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. 当您想从外部域加载数据时,可以使用JSONP替代Ajax,但这是服务器必须支持的功能。 If the server supports it, instead of returning (for example) simple JSON: 如果服务器支持,则不返回(例如)简单的JSON:

{"foo": 42}

it would wrap it in callbackName(...); 它将包装在callbackName(...); to create a JS script with a single function call: 使用单个函数调用创建JS脚本:

callbackName({"foo": 42});

The actual function name is taken from the GET parameter callback . 实际的函数名称来自GET参数callback

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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