javascript JSONP 回调函数未定义

发布于 2024-10-08 19:18:41 字数 510 浏览 0 评论 0原文

(
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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

千里故人稀 2024-10-15 19:18:41

JSON-P 使用 script 元素添加到文档中,因此其中的函数调用必须引用全局范围内存在的函数。

turnLongURL 仅限于 restoreURL 的范围,因为它是在其中定义的。

将函数声明移动到全局范围,或者将其更改为函数语句,这样:

window.turnLongURL = function (data) {

……应该可以使其工作。

请记住,如果在第一个返回之前发出多个 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 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文