【问题标题】:javascript JSONP callback function not definedjavascript JSONP回调函数未定义
【发布时间】:2015-03-11 19:05:10
【问题描述】:
(
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 没有定义

这是为什么呢?

【问题讨论】:

    标签: javascript jsonp


    【解决方案1】:

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

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

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

    window.turnLongURL = function (data) {
    

    …应该让它工作。

    如果在第一次返回之前发送多个 JSON-P 请求,请记住考虑竞争条件的可能性。

    【讨论】:

    • 它仍然无法正常工作,并且一直说 turnLongURL 未定义...如果我正在编辑油脂猴子脚本有什么不同吗?
    • @Quentin 说明 jsonp 竞争条件的最佳方法是什么?
    猜你喜欢
    • 1970-01-01
    • 2014-02-10
    • 2011-03-01
    • 2013-11-19
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 2012-02-23
    相关资源
    最近更新 更多