(
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/