最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript JSONP callback function not defined - Stack Overflow

programmeradmin3浏览0评论
(
function restoreURL() {
    function turnLongURL(data) {
        window.location = data.url;
    }

    var shortUrl = window.location.href;

    var url = "/?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?

(
function restoreURL() {
    function turnLongURL(data) {
        window.location = data.url;
    }

    var shortUrl = window.location.href;

    var url = "http://json-longurl.appspot./?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?

Share Improve this question asked Dec 24, 2010 at 19:49 Ya ZhuangYa Zhuang 4,66033 silver badges40 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

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.

发布评论

评论列表(0)

  1. 暂无评论