/*
* define a javascript class, this is its constructor.
* For using this class object, make sure define an outer Ajax Component(may be an object) "ajaxComponent",
* which must has two methods: handleMessage(req) and handleError(req),
* for responsing handling successful message and error message.
*/
AjaxObject = function(ajaxComponent, url, method){
this.ajaxComponent = ajaxComponent;
this.url = url;
this.method = method ? method : "POST"; //default use "post" method
}
AjaxObject.prototype = {
sendRequest: function() {
var req = this.initReqInstance();
if(req){
var oThis = this; //must declare a local reference to 'this' for closure
req.onreadystatechange = function(){ //appoint callback function
oThis.handleResponse(req);
};
try {
req.open(this.method, this.url, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
} catch (e) {
alert(e);
}
req.send(null);
}
}, //!Notice: shound be separated by ','
initReqInstance: function(req){
var req;
if(window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE browsers
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (err) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return req;
}, //!Notice: shound be separated by ','
handleResponse: function(req){
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
this.ajaxComponent.handleMessage(req);
} else { // Error handling
this.ajaxComponent.handleError(req);
}
}
} //the last key:value pair should not have ','
};
|