Created
June 3, 2011 07:13
-
-
Save jiggliemon/1006000 to your computer and use it in GitHub Desktop.
Simple jsonp helper.
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
(function(global,namespace){ | |
if(!namespace) namespace = {}; | |
if (!namespace._jsonp_id) namespace._jsonp_id = 0; | |
namespace.JSONP = function(url, options) { | |
if (!namespace._jsonp_id) { | |
namespace._jsonp_id = 0; | |
} | |
var doc = document, | |
head = doc.getElementsByTagName('head')[0] || doc.body, | |
script = doc.createElement('script'), | |
token = '__jsonp_' + namespace._jsonp_id; | |
options = namespace.extend(options, { | |
params: {}, | |
callback_name: 'callback', | |
callback: false | |
}); | |
console.log(options); | |
return { | |
request: function(params) { | |
params = new Hash(namespace.extend(params||{},options.params)); | |
if (options.callback) { | |
params.set(options.callback_name, token); | |
window[token] = options.callback; | |
} | |
if (params.size() > 0) { | |
url = url.replace(/(\?|$)/, '?'+ params.toQueryString()); | |
} | |
script.src = url; | |
// clean up on load: remove script tag, null script variable and delete global callback function | |
script.onload = function() { | |
script.remove(); | |
script = null; | |
delete window[token]; | |
}; | |
head.appendChild(script); | |
// callback name should be unique | |
namespace._jsonp_id++; | |
} | |
}; | |
}; | |
})(window,namespace); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment