Javascript Ajax implementation code

Source: Internet
Author: User

What are the advantages and disadvantages of the current Ajax framework? Let's talk about it later:
1. Ajax. js CopyCode The Code is as follows :/*
Ajax v1.4
Hjf 2009-7-5
*/
Function ajaxdo (){

This. httprequest = NULL;

This. openmethod = NULL; // The HTTP request method, which is get, post, or head.

This. Openurl = NULL; // It is the target URL. Based on security considerations, this URL can only be of the same domain, otherwise the error "no permission" will be prompted.

This. openasync = NULL; // specifies whether to continue executing the following code during the waiting time for the server to return information. If it is false, the execution will not continue until the server returns information. The default value is true.

This. processrequestfunction = function (_ httprequest) {return;} // function entry for processing returned information

This. processrequestparam = NULL; // additional parameter for processing access information

This. loadingimg = NULL; // The uploaded image, which is generally a. gif animation.

// Initialize httprequest
This. inithttprequest = function (){
VaR HTTP;

// Try {
// HTTP = new activexobject ("msxml2.xmlhttp ");
//} Catch (e ){
// Try {
// HTTP = new activexobject ("Microsoft. XMLHTTP ");
//} Catch (e ){
// HTTP = false;
//}
//}

Try {
If (window. activexobject ){
For (VAR I = 5; I --){
Try {
If (I = 2 ){
HTTP = new activexobject ("Microsoft. XMLHTTP ");
} Else {
HTTP = new activexobject ("msxml2.xmlhttp." + I + ". 0 ");
}
Break;
} Catch (e ){
// Alert (I );
HTTP = false;
}
}
} Else if (window. XMLHttpRequest ){
HTTP = new XMLHttpRequest ();
If (HTTP. overridemimetype ){
HTTP. overridemimetype ("text/XML ");
}
}
} Catch (e ){
HTTP = false;
}

If (! HTTP ){
Alert ("XMLHTTPRequest object instance cannot be created ");
Return HTTP;
}

This. httprequest = http;
Return HTTP;
}

// Detect this. httprequest
This. checkhttprequest = function (){
If (! This. httprequest ){
Return this. inithttprequest ();
}
Return this. httprequest;
}

// Modify the mime category
// HTTP. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded"); // If You Want to upload a file or post content to the server
// HTTP. setRequestHeader ("Content-Type", "text/XML ");
// HTTP. setRequestHeader ("Content-Type", "gb2312 ");
This. setRequestHeader = function (MIME ){
If (! This. checkhttprequest ()){
Return false;
}
Try {
This. httprequest. setRequestHeader ("Content-Type", mime );
Return true;
} Catch (e ){
If (E instanceof error ){
Alert ("Incorrect MIME category modification ");
Return false;
}
}
}

// Set the event trigger for changing the status
This. setonreadystatechange = function (funhandle, Param ){
If (! This. checkhttprequest ()){
Return false;
}
This. processrequestfunction = funhandle;
This. processrequestparam = Param;
Return true;
}

This. setloadingimg = function (imgid ){
This. loadingimg = imgid;
}

// establish an HTTP connection
// open ("method", "url" [, asyncflag [, "username" [, "password"])
This. open = function (method, URL, async, username, psw) {
If (! This. checkhttprequest () {
return false;
}< br> This. openmethod = method;
This. openurl = URL;
This. openasync = async;
If (this. openmethod = NULL) | (this. openmethod. touppercase ()! = "Get") & (this. openmethod. touppercase ()! = "Post") & (this. openmethod. touppercase ()! = "Head") {
alert ("specify the HTTP request method, such as get, post, or head");
return false;
}< br> If (this. openurl = NULL) | (this. openurl = "") {
alert ("specify the target URL");
return false;
}< br> try {
This. httprequest. open (this. openmethod, this. openurl, this. openasync, username, psw);
}catch (e) {
If (E instanceof error) {
alert ("unable to establish HTTP Connection ");
return false;
}< BR >}

If (this. openmethod. touppercase () = "Post "){
If (! This. setRequestHeader ("application/X-WWW-form-urlencoded ")){
Alert ("failed to modify mime category ");
Return false;
}
}

If (this. openasync) {// asynchronous mode,ProgramContinue execution
If (this. processrequestfunction = NULL ){
Alert ("specify the function for processing returned information ");
Return false;
}
VaR _ http_request_ajax = This. httprequest;
VaR _ this_ajax = this;
This. httprequest. onreadystatechange = function (){
If (_ http_request_ajax.readystate = 4 ){
If (_ http_request_ajax.status = 200 ){
_ This_ajax.processrequestfunction (_ http_request_ajax, _ this_ajax.processrequestparam, _ this_ajax.loadingimg );
} Else {
Alert ("the page you requested has an exception. ");
Return false;
}
}
}
}

If (this. loadingimg! = NULL ){
Funshow (this. loadingimg );
}

Return true;
}

// Send an HTTP request to the server
// Format: Name = Value & anothername = othervalue & so = on
This. Send = function (idata ){
If (! This. checkhttprequest ()){
Return false;
}
VaR DATA = NULL;
If (this. openmethod. touppercase () = "Post "){
Data = funescapeall (idata );
}
Try {
This. httprequest. Send (data );
Return true;
} Catch (e ){
If (E instanceof error ){
Alert ("failed to send HTTP request to server ");
Return false;
}
}
}

// Process the information returned by the server
This. getresponsetext = function (type ){
If (! This. checkhttprequest ()){
Return false;
}
If (this. httprequest. readystate = 4 ){
If (this. httprequest. Status = 200 ){
If (type! = NULL) & (type. touppercase () = "XML ")){
Return this. httprequest. responsexml;
}
Return this. httprequest. responsetext;
} Else {
Alert ("the page you requested has an exception. ");
Return false;
}
}
}

// Stop the current request
This. Abort = function (){
If (! This. checkhttprequest ()){
Return false;
}

If (this. loadingimg! = NULL ){
Funhide (this. loadingimg );
}

If (this. httprequest. readystate> 0 & this. httprequest. readystate <4 ){
This. httprequest. Abort ();
}
}

}

// ================================================ ========================================================== ========
// Public Functions
// ================================================ ========================================================== ========
Function $ (_ OBJ ){
VaR O;
If (typeof (_ OBJ )! = "String ")
Return _ OBJ;
Else {
Try {
Document. All;
Try {
O = Document. All (_ OBJ );
} Catch (e ){
Return NULL;
}
} Catch (EE ){
Try {
O = Document. getelementbyid (_ OBJ );
} Catch (e ){
Return NULL;
}
}
Return O;
}
}

Function funescapeall (STR ){
VaR T = "&";
VaR S = Str. Split (t );
If (S. Length <= 0) return STR;
For (VAR I = 0; I <S. length; I ++ ){
S [I] = funescapeone (s [I]);
}
Return S. Join (t );
}

Function funescapeone (STR ){
VaR I = Str. indexof ("= ");
If (I =-1) return STR;
VaR T = urlencode (Str. substr (I + 1 ));
Return Str. substring (0, I + 1) + T;
}

Function urlencode (STR ){
Return encodeuricomponent (STR );
/*
Return escape (STR). Replace (/\ +/g, "% 2B ").
Replace (/\ "/g," % 22 ").
Replace (/\ '/g, "% 27 ").
Replace (// G, "% 2f ");
*/
}

Function funescapexml (content ){
If (content = undefined)
Return "";
If (! Content. Length |! Content. charat)
Content = new string (content );
VaR result = "";
VaR length = content. length;
For (VAR I = 0; I <length; I ++ ){
VaR CH = content. charat (I );
Switch (CH ){
Case '&':
Result + = "&";
Break;
Case '<':
Result + = "<";
Break;
Case '> ':
Result + = "> ";
Break;
Case '"':
Result + = """;
Break;
Case '\'':
Result + = "'";
Break;
Default:
Result + = CH;
}
}
Return result;
}

Function funshow (_ OBJ ){
If (typeof (_ OBJ) = "object ")
_ Obj. style. Visibility = "inherit ";
Else
$ (_ OBJ). style. Visibility = "inherit ";
}

Function funhide (_ OBJ ){
If (typeof (_ OBJ) = "object ")
_ Obj. style. Visibility = "hidden ";
Else
$ (_ OBJ). style. Visibility = "hidden ";
}

Function alert (STR ){
Alert (STR );
// Window. Status = STR;
}

/*

Example:

Function processrequest (http_request, _ Val, _ loading_img ){
If(http_request.responsexml.doc umentelement ){
// Alert(decodeuricomponent(http_request.responsexml.doc umentelement. XML ));
} Else {
// Alert (decodeuricomponent (http_request.responsetext ));
}
Alert (_ Val );
Funhide (_ loading_img );
}

1. Get
VaR Ajax = new ajaxdo ();

Ajax. setloadingimg (_ loading_img );
Ajax. setonreadystatechange (processrequest, _ Val );
Ajax. Open ("get", URL, true); // in asynchronous mode, the program continues to run
Ajax. Send ("");

Ajax. Open ("get", URL, false); // non-asynchronous mode, the program waits
Ajax. Send ("");
VaR xml_doc = Ajax. getresponsetext ("XML ");
VaR text_doc = Ajax. getresponsetext ("text ");

2. Post
VaR Ajax = new ajaxdo ();

Ajax. setloadingimg (_ loading_img );
Ajax. setonreadystatechange (processrequest, _ Val );
Ajax. Open ("Post", URL, true); // in asynchronous mode, the program continues to run
Ajax. Send (data );

Ajax. Open ("Post", URL, false); // non-asynchronous mode, the program waits
Ajax. Send (data );
VaR xml_doc = Ajax. getresponsetext ("XML ");
VaR text_doc = Ajax. getresponsetext ("text ");

Note: When the client sends information with a Chinese or HTML Script, The sent information must be called: encodeuricomponent function, for example:
VaR DATA = encodeuricomponent ($ ('message'). value );
Actually, it is called twice, and the Ajax class is called again internally.

The server (Java version) needs to perform the following transcoding:
String message = request. getparameter ("message ");
Message = urldecoder. Decode (message, "UTF-8 ");

*/

Note: When the client sends information with a Chinese or HTML Script, The sent information must be called: encodeuricomponent function, for example:
VaR DATA = encodeuricomponent ($ ('message'). value );
Actually, it is called twice, and the Ajax class is called again internally.

The server (Java version) needs to perform the following transcoding:

string message = request. getparameter ("message");
message = urldecoder. decode (message, "UTF-8");
2366demo.html copy Code the code is as follows:



Ajax class


<Body>
<Div id = "layer1"> </div>
<SCRIPT type = "text/JavaScript" Language = "JavaScript"> <! --
Function processrequest (http_request, _ Val, _ loading_img ){
Alert(http_request.responsexml.doc umentelement. XML );
// Alert (http_request.responsetext );
Funhide (_ loading_img );
}
// --> </SCRIPT>
<SCRIPT type = "text/JavaScript" Language = "JavaScript"> <! --
VaR url = "http://www.w3schools.com/xml/simple.xml ";
VaR DATA = "";

VaR Ajax = new ajaxdo ();

Function btnajax1 (){
// Var Ajax = new ajaxdo ();
// Ajax. inithttprequest ();
Ajax. Abort ();

Ajax. setloadingimg (document. getelementbyid ("layer1 "));
Ajax. setonreadystatechange (processrequest );
Ajax. Open ("get", URL, true); // in asynchronous mode, the program continues to run
Ajax. Send ("");
}

Function btnajax2 (){
// Var Ajax = new ajaxdo ();
// Ajax. inithttprequest ();
Ajax. Abort ();

Ajax. Open ("get", URL, false); // non-asynchronous mode, the program waits
Ajax. Send ("");
Alert (Ajax. getresponsetext ("XML" cmd.doc umentelement. XML );
Alert (Ajax. getresponsetext ("text "));
}
// --> </SCRIPT>
<Button onclick = "btnajax1 ()"> asynchronous mode </button>
<Button onclick = "btnajax2 ()"> non-asynchronous mode </button>
</Body>
</Html>

3. Images

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.