In the past, many AJAX technologies such as EXT, prototype, and jQuery were used, but they are all open-source and encapsulated AJAX frameworks. I have never used pure AJAX, So I encapsulated an AJAX framework by referring to the prototyp object-oriented idea. Hope to give readers reference, help and comments.
Copy codeThe Code is as follows:
/*
* Self-encapsulated ajax
*
*
* @ Author Jiang song
* @ Version 1.00 $ date:
*
* History:
*
*/
Object. extend = function (destination, source ){
For (var property in source ){
Destination [property] = source [property];
}
Return destination;
};
Object. extend (String. prototype ,{
Include: function (pattern ){
Return this. indexOf (pattern)>-1;
},
StartsWith: function (pattern ){
Return this. indexOf (pattern) = 0;
},
EndsWith: function (pattern ){
Return this. lastIndexOf (pattern) = (this. length-pattern. length );
},
Empty: function (){
Return/^ \ s * $/. test (this) | this = undefined | this = null;
}
});
Object. extend (Array. prototype ,{
Each: function (iterator ){
Try {
For (var I = 0, length = this. length; I <length; I ++ ){
Iterator (this [I]);
}
} Catch (e ){
If (e! = 'Break') {throw e };
}
},
Clear: function (){
This. length = 0;
Return this;
},
First: function (){
Return this [0];
},
Last: function (){
Return this [this. length-1];
},
IndexOf: function (object ){
For (var I = 0, length = this. length; I <length; I ++ ){
If (this [I] = object) {return I };
}
Return-1;
},
Size: function (){
Return this. length;
},
Include: function (object ){
Var found = false;
This. each (function (value ){
If (value = object) {found = true; throw 'Break ';}
});
Return found;
}
});
Function $ (element ){
If (arguments. length> 1 ){
For (var I = 0, elements = [], length = arguments. length; I <length; I ++ ){
Elements. push ($ (arguments [I]);
}
Return elements;
}
If (typeof element = 'string '){
Element = document. getElementById (element );
}
Return element;
};
Var ajax = {
Transport: new Object (),
Options: new Object (),
GetTransport: function (){
If (window. ActiveXObject ){
Try {
Return new ActiveXObject ('msxm12. xmlhttp ');
} Catch (e ){
Try {
Return new ActiveXObject ('Microsoft. xmlhttp ');
} Catch (e ){}
}
} Else if (window. XMLHttpRequest ){
Try {
Return new XMLHttpRequest ();
} Catch (e ){}
}
},
SetOptions: function (options ){
Ajax. options = {
Method: 'get ',
Asynchronous: true,
ContentType: 'application/x-www-form-urlencoded ',
Encoding: 'utf-8 ',
Parameters :''
};
Object. extend (ajax. options, options );
Ajax. options. method = ajax. options. method. toUpperCase ();
},
Request: function (url, options ){
Ajax. transport = ajax. getTransport ();
Ajax. setOptions (options );
This. method = ajax. options. method;
Var params = ajax. options. parameters;
If (! ['Get', 'post']. include (this. method )){
This. method = 'get ';
}
If (this. method = 'get '){
Url = ajax. setParameters (url, params );
}
Try {
Ajax. transport. open (this. method, url, ajax. options. asynchronous );
Ajax. transport. onreadystatechange = ajax. stateChange;
Ajax. setRequestHeaders ();
This. body = this. method = 'post '? Params: null;
Ajax. transport. send (this. body );
} Catch (e ){}
},
StateChange: function (){
Try {
Var readyState = ajax. transport. readyState;
If (readyState = 4 ){
Var status = ajax. transport. status, transport = ajax, json = ajax. evalJSON ();
If (status = 200 ){
Ajax. options ['onsuccess'] (transport, json );
} Else {
Ajax. options ['onfailure'] (transport, json );
}
}
} Catch (e ){}
},
SetParameters: function (url, params ){
If (params & typeof params = 'string '){
Url + = (url. include ('? ')? '&':'? ') + Params;
} Else if (params & typeof params = 'object '){
For (var param in params ){
Url + = (url. include ('? ')? '&':'? ') + Param +' = '+ params [param];
}
}
Return url;
},
SetRequestHeaders: function (){
Var headers = {
'X-Requested-with': 'xmlhttprequest ',
'Accept': 'application/xml, text/xml, text/html, text/javascript, application/javascript, application/json, text/javascript, text/plain, */*',
'If-Modified-Since ': 'thu, 01 Jan 1970 00:00:00 gmt'
};
This. method = ajax. options. method;
If (this. method = 'post '){
Headers ['content-type'] = ajax. options. contentType +
(Ajax. options. encoding? '; Charset =' + ajax. options. encoding :'');
If (ajax. transport. overrideMimeType &&
(Navigator. userAgent. match (/Gecko \/(\ d {4})/) | [2005]) [1] <){
Headers ['connection'] = 'close ';
}
}
For (var name in headers ){
Ajax. transport. setRequestHeader (name, headers [name]);
}
},
EvalJSON: function (){
Try {
Return eval ('+ ajax. transport. responseText + ')');
} Catch (e ){}
}
};
Var Form = {
Serialize: function (element ){
Var elements = $ (element). all;
Var queryComponents = [];
For (var I = 0; I <elements. length; I ++ ){
Var parameter = null, method = elements [I]. tagName. toLowerCase ();
If (['input', 'select', 'textarea ']. include (method )){
Parameter = Form. Serializers [method] (elements [I]);
}
If (parameter! = Null & parameter. constructor = Array ){
Var key = encodeURIComponent (parameter [0]);
Var value = encodeURIComponent (parameter [1]);
QueryComponents. push (key + '=' + value );
}
}
Return queryComponents. join ('&');
},
Request: function (options ){
Var params = this. toQueryParams (options. parameters );
Options. parameters = this. serialize (this. form );
If (params ){
Options. parameters = options. parameters. concat ('&' + params );
}
If ($ (this. form). method ){
Options. method = $ (this. form). method;
}
Return new ajax. request ($ (this. form). action, options );
},
ToQueryParams: function (params ){
Var queryComponents = [];
If (params & typeof params = 'string '){
QueryComponents. push (encodeURIComponent (params ));
} Else if (params & typeof params = 'object '){
For (var param in params ){
Var key = encodeURIComponent (param );
Var value = encodeURIComponent (params [param]);
QueryComponents. push (key + '=' + value );
}
}
Return queryComponents. join ('&');
}
};
Form. Serializers = {
Input: function (element ){
Switch (element. type. toLowerCase ()){
Case 'checkbox ':
Case 'Radio ':
Return this. inputSelector (element );
Default:
Return this. textarea (element );
}
},
InputSelector: function (element ){
If (element. checked ){
Return [element. name, element. value];
}
},
Textarea: function (element ){
Return [element. name, element. value];
},
Select: function (element ){
Return this [element. type = 'select-one '?
'Selectone': 'selectone'] (element );
},
SelectOne: function (element ){
Var value = null, option, index = element. selectedIndex;
If (index> = 0 ){
Option = element. options [index];
Value = option. value = (undefined | '')? Option. text: option. value;
}
Return [element. name, value];
},
Selectparameters: function (element ){
Var value = [];
For (var I = 0; I <element. length; I ++ ){
Var option = element. options [I];
If (option. selected ){
Var optvalue = option. value = (undefined | '')? Option. text: option. value;
Value. push (optvalue );
}
}
Return [element. name, value];
}
};
Function $ F (element ){
This. form = element;
}
Object. extend ($ F. prototype, Form );
/*************************************** ***********************
* Test functions
*/
Function onTest (){
// Get submission method
Var params = new Object ();
Params. ss = 'zhang san ';
New ajax. request ('ajax. do? Method = doGet ',{
OnSuccess: function (transport ){
Alert (transport. evalJSON (). xx)
},
Parameters: params
});
// Post form submission method
Var params = new Object ();
Params. idd = 1000;
Params. names = 'zhangsan'
New $ F ('form'). request ({
OnSuccess: function (transport ){
Alert (transport. evalJSON (). xx );
},
Parameters: params
});
}