Skip to content

Instantly share code, notes, and snippets.

@shakhal shakhal/call_jsonp.js
Last active Aug 29, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.