Created
September 26, 2013 15:48
-
-
Save tokkonopapa/6716103 to your computer and use it in GitHub Desktop.
Simple Ajax only for JSONP
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
/*! 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