Skip to content

Instantly share code, notes, and snippets.

@i-tengfei
Created August 11, 2015 02:55
Show Gist options
  • Save i-tengfei/e10319c766e48d3d2ed1 to your computer and use it in GitHub Desktop.
Save i-tengfei/e10319c766e48d3d2ed1 to your computer and use it in GitHub Desktop.
(function (root) {
var Ajax = function () {
this.setajax = {};
this.xmlhttp = {};
};
Ajax.prototype.open = function (s) {
var async, method, url, self = this;
this.setajax = s;
try {
if (!this.setajax.url) {
throw 'Você deve informar a url.';
}
if (typeof this.setajax === 'object') {
if (root.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
this.xmlhttp = new XMLHttpRequest();
} else {
// IE6, IE5
this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
this.xmlhttp.onreadystatechange = function () {
if (self.xmlhttp.readyState === 4 && self.xmlhttp.status === 200) {
if (self.setajax.dataType === 'json') {
try{
self.setajax.responseText = JSON.parse(self.xmlhttp.responseText);
} catch (err){
self.setajax.responseText = eval('(' + self.xmlhttp.responseText + ')');
}
} else {
self.setajax.responseText = self.xmlhttp.responseText;
}
}
};
method = this.setajax.method || 'GET';
url = this.setajax.url || root.location.href;
async = this.setajax.async || false;
this.xmlhttp.open(method, url, async);
this.xmlhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
if (this.setajax.data) {
this.xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
this.xmlhttp.send(JSON.stringify(this.setajax.data));
} else {
this.xmlhttp.send();
}
if (this.setajax.success && typeof this.setajax.success === 'function') {
this.setajax.success(this.setajax.responseText);
}
} else {
throw 'Você deve passar um objeto.';
}
} catch (e) {
if (this.setajax.error && typeof this.setajax.error === 'function') {
this.setajax.error(e);
}
}
return this.xmlhttp;
};
root['Ajax'] = new Ajax();
}(this));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment