Objective: To directly use prototype because some modules in the blog program need to use ajax. js is relatively large (more than 40 k), and only uses the ajax function. Therefore, to reduce the download burden, you cannot change the prototype already in use. the code written under the js framework can only follow the prototype style and write an ajax class by yourself to achieve zero-cost porting of the framework.
The new ajax class is as follows:
Var Ajax = {xmlhttp: function (){
Try {
Return new ActiveXObject ('msxml2. xmlhttp ');
} Catch (e ){
Try {
Return new ActiveXObject ('Microsoft. xmlhttp ');
} Catch (e ){
Return new XMLHttpRequest ();
}
}
}
};
Ajax. Request = function (){
If (arguments. length <2) return;
Var _ p = {asynchronous: true, method: "GET", parameters: ""}; // default option
For (var key in arguments [1]) {// custom option overwrite default option
_ P [key] = arguments [1] [key];
}
Var _ x = Ajax. xmlhttp (); // xml obj
Var _ url = arguments [0]; // str
If (_ p ["parameters"]. length> 0) _ p ["parameters"] + = '& _ = ';
If (_ p ["method"]. toUpperCase () = "GET") _ url + = (_ url. match (/\? /)? '&':'? ') + _ P ["parameters"];
_ X. open (_ p ["method"], _ url, _ p ["asynchronous"]);
_ X. onreadystatechange = function (){
If (_ x. readyState = 4 ){
If (_ x. status = 200 ){
_ P ["onComplete"]? _ P ["onComplete"] (_ x ):"";
} Else {
_ P ["onError"]? _ P ["onError"] (_ x ):"";
}
}
}
If (_ p ["method"]. toUpperCase () = "POST") _ x. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded ");
_ X. send (_ p ["method"]. toUpperCase () = "POST "? _ P ["parameters"]: null );
};
This class is saved as a js file, which is smaller than 1 kb. Haha.
Call method:
Var myAjax = new Ajax. Request (
"Http: // localhost/abc. asp ",
{
Method: "post ",
Parameters: "demo = 123456789abc ",
OnComplete: function (xmlhttp ){
Alert (xmlhttp. responseText)
}
}
);
The Calling style is exactly the same as the original one!
Currently, this new class only has two callback functions: onComplete and onError. The Ajax class only has one Request method. After all, there is no need for so many applications in the blog program. The parameters property has a default value: {asynchronous: true, method: "GET", parameters: ""}, which can be known from this, if the asynchronous, method, and parameters are not input during the call, the default value is used for the class.