Skip to content

Instantly share code, notes, and snippets.

@tokkonopapa
Created September 26, 2013 15:48
Show Gist options
  • Save tokkonopapa/6716103 to your computer and use it in GitHub Desktop.
Save tokkonopapa/6716103 to your computer and use it in GitHub Desktop.
Simple Ajax only for JSONP
/*! Simple Ajax only for JSONP
*
* var args = {
* key: 'my-key',
* format: 'json'
* };
* myAjax.get('http://example.com/', args,
* function (response) {
* for (var key in response) {
* // key, response[key]
* }
* },
* function (err) {
* // err = {}
* }
* );
*/
myAjax = {
handler: [],
response: [],
serialize: function (base, args) {
var query = [];
for (var key in args) {
query.push(
encodeURIComponent(key) + '=' +
encodeURIComponent(args[key])
);
}
return base + '?' + query.join('&');
},
get: function (url, callback) {
var index = myAjax.handler.length;
var handler = 'myAjax.handler[' + index + ']';
// Regist response handler for each request
myAjax.handler.push(function (response) {
myAjax.response[index] = response;
});
var i = 1, args = {}, onerror;
if (typeof callback !== 'function') {
args = arguments[i++];
callback = arguments[i];
}
args.callback = handler;
onerror = arguments[++i];
var req = document.createElement('script');
// Regist user callback function
if (callback) {
req.onload = req.onreadystatechange = function () {
if (!this.readyState ||
this.readyState === "loaded" ||
this.readyState === "complete") {
this.onreadystatechange = null;
callback(myAjax.response[index]);
}
};
}
if (onerror) {
req.onerror = onerror;
}
req.async = true;
req.type = 'text/javascript';
req.src = myAjax.serialize(url, args);
document.body.appendChild(req);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment