(
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 badges1 Answer
Reset to default 8JSON-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.