Created
May 30, 2012 19:58
-
-
Save smonn/2838584 to your computer and use it in GitHub Desktop.
My XML HTTP Request function
This file contains 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
/*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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage example: