javascript JSONP回调函数未定义

Ya *_*ang 3 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); 
})();
Run Code Online (Sandbox Code Playgroud)

代码在上面,但是萤火虫告诉我,turnLongURL 没有定义

这是为什么?

Que*_*tin 8

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

turnLongURL仅限restoreURL于其内部定义的范围.

将函数声明移动到全局作用域,或将其更改为函数语句:

window.turnLongURL = function (data) {
Run Code Online (Sandbox Code Playgroud)

......应该让它发挥作用.

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

  • @David Freitas - 不要使用硬编码的函数名称. (2认同)