javascript JSONP 回调函数未定义
(
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);
})();
代码在上面,但是firebug告诉我,turnLongURL未定义,
为什么呢?
(
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
JSON-P 使用
script
元素添加到文档中,因此其中的函数调用必须引用全局范围内存在的函数。turnLongURL
仅限于restoreURL
的范围,因为它是在其中定义的。将函数声明移动到全局范围,或者将其更改为函数语句,这样:
……应该可以使其工作。
请记住,如果在第一个返回之前发出多个 JSON-P 请求,请考虑竞争条件的可能性。
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 ofrestoreURL
since it is defined inside it.Moving the function declaration to the global scope, or changing it to a function statement thus:
… 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.