I've created two simple methods: one to instantiate a new XMLHttpRequest
object and open the request and another to handle the request.
Can you please point out improvements that can be made or any shortcomings in my code?
ajax: function(opts) {
var xhr, method, body, constructor;
xhr = new XMLHttpRequest();
method = opts.body ? 'POST' : opts.method ? opts.method.toUpperCase() : 'GET';
if(opts.body) {
constructor = opts.body.constructor;
if(constructor === Object || constructor === String) {
body = opts.body;
}
}
this.ajaxComplete.call(xhr, opts);
xhr.open(method, opts.url, (opts.async === undefined ? true : false));
// Set the default request headers
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
if(opts.headers) {
for(var prop in opts.headers) {
xhr.setRequestHeader(prop, opts.headers[prop]);
}
}
xhr.send(body || null);
},
ajaxComplete: function(opts) {
var that = this,
data, complete;
that.onreadystatechange = function() {
if(that.readyState == 4) {
if(that.status == 200) {
data = (that.responseXML || that.responseText);
opts.success.call(that, data);
}
else {
data = (that.responseXML || that.responseText);
opts.error.call(opts, data, that.statusText, that.status);
}
}
}
}
constructor===Object
seems fishy \$\endgroup\$