I\'m developing a simple auxiliary class to send requests using XmlHttpRequest (code below). But I cant make it work. At google chrome, for example, I get the error INVALI
Regardless, you can simplify your SendRequest
method by creating a mixin instead of using a giant switch
.
XRequest.prototype.SendRequest = function(params) {
var defaultParams = {
async: true,
type: "",
url: "",
username: "",
password: "",
body: null,
success: null,
failure: null
};
for ( var i in defaultParams ) {
if ( defaultParams.hasOwnProperty(i) && typeof params[i] == "undefined" ) {
params[i] = defaultParams[i];
}
}
var that = this;
this.XHR.onreadystatechange = function() {
if ( that.XHR.readyState == 4 ) {
if ( that.XHR.status == 200 || that.XHR.status == 0 ) {
if ( params.success ) {
params.success(that.XHR);
}
} else {
if ( params.failure ) {
params.failure();
}
}
}
};
this.XHR.open(
params.type, parms.url, params.async, params.username, params.password
);
// It doesn't make sense to have a for/switch here when you're only handling
// one case
if ( params.setHeader ) {
var h = params.setHeader.split(":");
if ( h.length == 2) {
this.SetRequestHeader(h[0], h[1]);
}
}
this.XHR.send(params.body);
};
Also be careful: your existing for..in
loops have two distinct problems:
var
and causing a global to be created: for (e in args)
should be for (var e in args)
for..in
, you should always check to make sure that each key is a direct member of the object, and not something inherited inadvertently through prototype.
for ( var i in obj ) {
if ( obj.hasOwnProperty(i) ) {
// do stuff here
}
}