Created
November 29, 2010 15:48
-
-
Save bgrins/720105 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
An implementation of: http://javascriptweblog.wordpress.com/2010/11/29/json-and-jsonp/ | |
that handles multiple connections at once (don't want to replace the global callback if second | |
request is sent after the first, but returns before. | |
*/ | |
(function(global) { | |
var callbackCounter = 0; | |
var evalJSONP = function(callback) { | |
return function(data) { | |
var validJSON = false; | |
if (typeof data == "string") { | |
try {validJSON = JSON.parse(data);} catch (e) { | |
/*invalid JSON*/} | |
} else { | |
validJSON = JSON.parse(JSON.stringify(data)); | |
window.console && console.warn( | |
'response data was not a JSON string'); | |
} | |
if (validJSON) { | |
callback(validJSON); | |
} else { | |
throw("JSONP call returned invalid or empty JSON"); | |
} | |
} | |
} | |
global.safeJSONP = function(url, callback) { | |
var fn = 'JSONPCallback_' + callbackCounter++; | |
global[fn] = evalJSONP(callback); | |
url = url.replace('=JSONPCallback', '=' + fn); | |
var scriptTag = document.createElement('SCRIPT'); | |
scriptTag.src = url; | |
document.getElementsByTagName('HEAD')[0].appendChild(scriptTag); | |
} | |
})(this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment