未定义javascript JSONP回调函数

标签 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 没有定义

这是为什么?

最佳答案

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

turnLongURL 被限制在 restoreURL 的范围内,因为它是在其中定义的。

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

window.turnLongURL = function (data) {

…应该让它工作。

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

关于未定义javascript JSONP回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4528104/

相关文章:

javascript - 代码适用于不同于单个 html 文件的堆栈片段

typescript /Angular 2 : Cast JSON to interface with Observable & JSONP

jquery - 无法在 iPhone 应用程序上使用 PhoneGap 和 jQuery 获取 JSON 结果

api - 使用维基百科 API 获取图像 URL,但有些图像不返回 URL,为什么?

javascript - 如何使用 for 循环和拼接来删除单词,然后检查数组中的特定单词

javascript - 很难将 json 字符串从服务器转换为数组

javascript - Vue 2 : How to render Single File Components from Render Functions?

javascript - Node 错误 - 在 MakeCallback 中使用域属性已被弃用

jquery - 无法使用 jQuery 从跨域 JSON 服务 URL 检索数据

wcf - JQuery ajax JSONP跨域时POST改为GET