Last active
August 29, 2015 14:10
-
-
Save shakhal/0f4440fb3e59c71ec7bc to your computer and use it in GitHub Desktop.
Call JSONP
This file contains hidden or 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
function callJsonp(url, callbackFunc){ | |
var callbackName; | |
if (callbackFunc == null || callbackFunc.length == 0){ | |
callbackName = "dummy"; | |
} | |
else if (typeof(callbackFunc) == "function"){ | |
callbackName = functionName(callbackFunc); | |
if (window[callbackName] == undefined){ | |
callbackName = 'jsonp_callback_' + Math.floor(Math.random() * 100000); | |
window[callbackName] = callbackFunc; | |
} | |
} | |
getJsonp(url, callbackName); | |
} | |
/** | |
* perform GET on url, | |
* pass callback function to handle response | |
*/ | |
function getJsonp(url, callback){ | |
$.ajax({ | |
url: url, | |
// the name of the callback function | |
jsonpCallback: callback, | |
//timeout in ms | |
timeout : 30000, | |
// tell jQuery we're expecting JSONP | |
dataType: "jsonp", | |
// work with the response | |
success: function( response ) { | |
}, | |
error: function(jqXHR, textStatus, errorThrown){ | |
if (textStatus == "parsererror"){ | |
alert("Parsing error, please retry"); | |
} | |
else if (textStatus == "error"){ | |
alert("Error: " + errorThrown); | |
} | |
else if (textStatus == "timeout"){ | |
alert("Request timedout, please retry"); | |
} | |
else if (textStatus == "abort"){ | |
alert("Error: Action aborted" ); | |
} | |
else{ | |
alert("Error performing action"); | |
} | |
} | |
}); | |
} | |
function functionName(fun) { | |
var ret = fun.toString(); | |
ret = ret.substr('function '.length); | |
ret = ret.substr(0, ret.indexOf('(')); | |
return ret; | |
} | |
function dummy(){} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment