Last active
August 23, 2016 03:10
-
-
Save kotarok/4e7d0e5dfe574ab8bf40cdc7be65fcd3 to your computer and use it in GitHub Desktop.
Simple JSONP caller. Load JSON data as JSONP with given function.
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
var JSONP = function(apiurl, params, options) { | |
if (params) { | |
this.apiurl = this.constructURL_(apiurl, params); | |
} | |
this.conf = { | |
callbackKey: 'callback', | |
callbackName: 'uni', | |
paramDelimiter: '&' | |
}; | |
if (options) { | |
Object.keys(options).forEach(function(option) { | |
this.conf[option] = options[option]; | |
}); | |
} | |
this.apiurl = apiurl.replace( | |
RegExp(this.conf.paramDelimiter + '?' + this.conf.callbackKey + '='), ''); | |
}; | |
JSONP.prototype.buildParamStr_ = function(obj) { | |
if (!obj) return false; | |
var paramSets = []; | |
Object.keys(obj).forEach(function(key) { | |
paramSets.push(key + '=' + obj[key]); | |
}); | |
return paramSets.join(this.conf.paramDelimiter); | |
}; | |
JSONP.prototype.constructURL_ = function(baseURL, params) { | |
return baseURL.replace(/&?$/, | |
this.conf.paramDelimiter + this.buildParamStr_(params)); | |
}; | |
JSONP.discard = function(callbackName) { | |
delete window[callbackName]; | |
var script = document.getElementById(callbackName); | |
script.parentNode.removeChild(script); | |
}; | |
JSONP.prototype.call = function(callback, params) { | |
var callbackKey = this.conf.callbackKey; | |
var delimiter = this.conf.paramDelimiter; | |
var callbackName = this.conf.callbackName + Date.now(); | |
var callbackParam = callbackKey + '=' + callbackName; | |
window[callbackName] = function(json) { | |
callback(json); | |
JSONP.discard(callbackName); | |
}; | |
params[callbackKey] = callbackName; | |
var script = document.createElement('script'); | |
script.src = this.apiurl + delimiter + this.buildParamStr_(params); | |
script.id = callbackName; | |
document.body.appendChild(script); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment