(
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);
})();
代码在上面,但是萤火虫告诉我,turnLongURL没有定义
这是为什么?
解决方法:
JSON-P使用脚本元素添加到文档中,因此其中的函数调用必须引用存在于全局范围内的函数.
turnLongURL仅限于restoreURL的范围,因为它在其中定义.
将函数声明移动到全局作用域,或将其更改为函数语句:
window.turnLongURL = function (data) {
……应该让它发挥作用.
如果在第一次返回之前发出多个JSON-P请求,请记住考虑竞争条件的可能性.