Skip to content

Instantly share code, notes, and snippets.

@rbarros
Last active April 5, 2016 20:18
Show Gist options
  • Save rbarros/2776240 to your computer and use it in GitHub Desktop.
Save rbarros/2776240 to your computer and use it in GitHub Desktop.
Ajax
/*!
* Ajax JavaScript Library v0.5.12
* http://public.ramon-barros.com/
*
* Copyright 2012, Ramon Barros
* Licensed
*
* Includes ajax.js
* http://.com/
* Copyright 2012,
*
*
* Date: Wed May 03 13:17:00 2012 -0300
*/
(function (root) {
'use strict';
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') {
self.setajax.responseText = JSON.parse(self.xmlhttp.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));
/*
var ajax = Ajax.open({
method: 'GET',
url: 'http://localhost/',
dataType: 'json',
//data: { id: 1 },
success: function (json) {
console.log(json);
}
});
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment