Skip to content

Instantly share code, notes, and snippets.

@smonn
Created May 30, 2012 19:58
Show Gist options
  • Save smonn/2838584 to your computer and use it in GitHub Desktop.
Save smonn/2838584 to your computer and use it in GitHub Desktop.
My XML HTTP Request function
/*jslint browser: true, windows: true, indent: 2 */
// async: whether the request is asynchronuos or not
// cached: set to false to ignore browser cache
// method: the http method to use
// data: key value pairs, e.g. foo=1&bar=2
// url: the absolute or relative url to send the request to
// success: the success function, will receive the XHR object
// failure: the failure function, will receive the XHR object
// prepare: set to a function to set additional parameters to the xhr object, it should return the xhr object
(function (w) {
'use strict';
var HttpRequest = function (options) {
var that = this,
def = {
async: true,
cached: true,
method: 'GET',
data: null,
url: '',
success: function () {},
failure: function () {},
prepare: null
},
prop;
for (prop in def) {
if (def.hasOwnProperty(prop) && options[prop] === undefined) {
options[prop] = def[prop];
}
}
this.options = options;
this.request = null;
if (window.XMLHttpRequest) {
this.request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
this.request = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e1) {
try {
this.request = new ActiveXObject('Microsoft.XMLHTTP');
} catch (e2) {}
}
}
if (this.options.cached === false) {
this.options.url += ((/\?/).test(this.options.url) ? '&' : '?') + (new Date()).getTime();
}
if (typeof this.options.prepare === 'function') {
this.request = this.options.prepare(this.request);
}
this.request.onreadystatechange = function () {
if (that.request.readyState === 4) {
if (that.request.status === 200) {
that.options.success(that.request);
} else {
that.options.failure(that.request);
}
}
};
};
w.HttpRequest = HttpRequest;
HttpRequest.prototype.send = function () {
this.request.open(this.options.method, this.options.url, this.options.async);
if (typeof this.options.data === 'string' && this.options.data.length > 0) {
this.request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
this.request.send(this.options.data);
};
}(window));
@smonn
Copy link
Author

smonn commented May 30, 2012

Usage example:

var xhr = new HttpRequest({
  async: true,
  method: 'POST',
  data: 'foo=bar',
  url: 'api.php',
  success: function (xhr) { console.log(xhr); },
  failure: function (xhr) { console.warn(xhr); }
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment