Skip to content

Instantly share code, notes, and snippets.

@shakhal
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shakhal/0f4440fb3e59c71ec7bc to your computer and use it in GitHub Desktop.
Save shakhal/0f4440fb3e59c71ec7bc to your computer and use it in GitHub Desktop.
Call JSONP
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