Proficient in Ajax technology

Source: Internet
Author: User
I can't help myself with the Ajax name, probably (Active JavaScript action XML, to put it bluntly, JavaScript, XMLHTTP, and xmldom technologies and website background are used to process user operations. [Chinese webmaster site]

I will explain how to use Ajax technology for development in three steps.

Chinaz.com

 

1. Use JavaScript to operate the XMLHTTP object chinaz.com

2. Server Department's response to XMLHTTP request (PhP example) chinaz.com

Iii. Usage of xmldom

[Chinese webmaster site]

 

First part: [Chinese webmaster station]

1. Use JavaScript to operate the XMLHTTP object chinaz.com

In IE7, Mozilla, Firefox, and other browsers, JavaScript has the built-in XMLHTTPRequest object, but ie5 + does not. You need to start it using the following method:
// IE 6
Try {xhttp = new activexobject ("msxml2.xmlhttp";} catch (e ){;}
// Ie5 +
If (xhttp = NULL) Try {xhttp = new activexobject ("Microsoft. XMLHTTP";} catch (e ){;}

[Chinese webmaster site]

 

Considering the compatibility of different browsers, starting an XMLHTTP generally requires the following method: chinaz.com

Code: [copy to clipboard] var xhttp = NULL; chinaz.com

If (window. XMLHttpRequest) {// IE7, Mozilla, Firefox, and other browsers have built-in objects.

Chinaz.com

 

Xhttp = new XMLHttpRequest ();

} Else if (window. activexobject) {// IE6, ie5

[Chinese webmaster site]

 

Try {xhttp = new activexobject ("msxml2.xmlhttp");} catch (e ){;}

If (xhttp = NULL) Try {xhttp = new activexobject ("Microsoft. XMLHTTP");} catch (e ){;}

} Chinaz.com

XMLHTTP is generally used in the following order: chinaz.com

1. initialize the XMLHTTP object (above); [Chinese webmaster site]

2. Open the link [Chinese webmaster site]

Method

[Chinese webmaster site]

 

Xhttp. Open ("get", purl, true); chinaz.com

Parameter 1: send data using get or post

[Chinese webmaster site]

 

Parameter 2: request URL (only resources on your server can be requested. Generally, browser security restrictions cannot read cross-Origin data)

Chinaz.com

 

Parameter 3. True indicates asynchronous transmission (you can perform other operations before the server returns information), and false indicates blocking transmission. [Chinese webmaster site]

3. Set the HTTP request header to be sent

[Chinese webmaster site]

 

Method:

[Chinese webmaster site]

 

Xhttp. setRequestHeader (Key, value );

[Chinese webmaster site]

 

Generally, the default headers to be sent are: xhttp. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded"; [Chinese webmaster site]

This type of request header is used to send text data, and JavaScript is sent in Unicode by default, and another form is: xhttp. setRequestHeader ("Content-Type", "multipart/form-Data"; this indicates sending binary data. For security reasons, JavaScript generally cannot send data in this way, this header is generally useless.

[Chinese webmaster site]

 

If your website has enabled anti-leech protection using the refer parameter, you must use this method to specify the refer parameter. If you need to log on to the website to perform an operation, you must specify the cookie request header. [Chinese webmaster site]

4. Send data

Chinaz.com

 

Method: xhttp. Send (postdata); chinaz.com

For get attacker requests, you do not need to specify postdata and directly use test. php? A = A & B = B. [Chinese webmaster site]

If it is post, you need to use key1 = value2 & key2 = value2 to process the data, merge it into the postdata string, and then send it. [Chinese webmaster site]

Note:

Chinaz.com

 

By default, JavaScript sends data in unicode format, and the returned data must be in UTF-8 format. Therefore, when sending data, you must use the escape () function to process postdata and URL values, these values must be restored on the server and Unicode is converted to page encoding values. Therefore, JSP or Asp.net is simple, but If PHP is used for processing, I will teach you how to do it later. [Chinese webmaster site]

5. confirm that the server has returned the required information for download.

Chinaz.com

 

[1] if the request is blocked, you can directly use if (xhttp. readystate = 4) to determine whether the request is complete. Chinaz.com

The specific attribute value of readystate is:
0: no open
1 No send
2 unknown status
3. Transmitting
4. transfer completed [Chinese webmaster station]

Of course, for the sake of protection, you also need to add another judgment, that is, if (xhttp. Status = 200), status is the return header code in the HTTP protocol.

Chinaz.com

 

1xx indicates (forgot)
2XX indicates successful information
3xx indicates page Transfer
The 4xx page does not exist.
5xx indicates various Server errors chinaz.com

If your page does not have special processing, we usually use if (xhttp. Status = 200) to make sure that the returned content is correct.

[Chinese webmaster site]

 

[2] If asynchronous transmission is used, the onreadystatechange event must be used to listen

Chinaz.com

 

Xhttp. onreadystatechange = function ()
{
// Determine the blocking method above
If (myajax. xhttp. readystate = 4 ){
If (myajax. xhttp. Status = 200 ){
// Subsequent operations to be performed
}
}
}

Chinaz.com

 

6. Obtain the returned result chinaz.com

Attribute:
[1] xhttp. responsebody;
[2] xhttp. responsestream;
[3] xhttp. responsexml;
[4] xhttp. responsetext;

[Chinese webmaster site]

 

Among them, 1 and 2 are binary, which are rarely used, and 4 is not needed.

Chinaz.com

 

If the server is not surprised, [3] returns an xmldom object.

[Chinese webmaster site]

 

2. Server Department's response to XMLHTTP requests (PhP example) [Chinese webmaster site]

To simplify the operation, the XMLHTTP operations are encapsulated as a class.

Chinaz.com

 

Code: [copy to clipboard] function dedeajax (witeokfunc) {// witeokfunc is an asynchronous state event processing function [Chinese webmaster site]

// XMLHTTP and xmldom objects
This. xhttp = NULL;
This. xdom = NULL;

[Chinese webmaster site]

 

// Key-value pairs for sending data via post or get
This. Keys = array ();
This. Values = array ();
This. keycount =-1;

Chinaz.com

 

// HTTP Request Header
This. rkeys = array ();
This. rvalues = array ();
This. rkeycount =-1;
// Request Header type
This. Rtype = 'text ';

Chinaz.com

 

// Initialize XMLHTTP
If (window. XMLHttpRequest) {// IE7, Mozilla, Firefox, and other browsers have built-in objects.
This. xhttp = new XMLHttpRequest ();
} Else if (window. activexobject) {// IE6, ie5
Try {This. xhttp = new activexobject ("msxml2.xmlhttp");} catch (e ){}
If (this. xhttp = NULL) Try {This. xhttp = new activexobject ("Microsoft. XMLHTTP") ;}catch (e ){}
}
This. xhttp. onreadystatechange = witeokfunc;
// RS: responsebody, responsestream, responsexml, and responsetext [Chinese webmaster station]

// The following are member functions.
//--------------------------------

Chinaz.com

 

// Initialize xmldom
This. initxdom = function (){
VaR OBJ = NULL;
If (typeof (domparser )! = "Undefined") {// Gecko, Mozilla, Firefox
VaR parser = new domparser ();
OBJ = parser. parsefromstring (xmltext, "text/XML ");
} Else {// IE
Try {OBJ = new activexobject ("msxml2.domdocument");} catch (e ){}
If (OBJ = NULL) Try {OBJ = new activexobject ("Microsoft. xmldom");} catch (e ){}
}
This. xdom = OBJ;
};

Chinaz.com

 

// Add a post or get key-Value Pair
This. addkey = function (skey, svalue ){
This. keycount ++;
This. Keys [This. keycount] = skey;
This. Values [This. keycount] = escape (svalue );
};

[Chinese webmaster site]

 

// Add an HTTP request header key-Value Pair
This. addhead = function (skey, svalue ){
This. rkeycount ++;
This. rkeys [This. rkeycount] = skey;
This. rvalues [This. rkeycount] = svalue;
};

[Chinese webmaster site]

 

// Clear the hash table parameters of the current object
This. clearset = function (){
This. keycount =-1;
This. Keys = array ();
This. Values = array ();
This. rkeycount =-1;
This. rkeys = array ();
This. rvalues = array ();
};

Chinaz.com

 

// Send the HTTP Request Header
This. sendhead = function (){
If (this. rkeycount! =-1) {// send the User-Defined Request Header
For (; I <= This. rkeycount; I ++ ){
This. xhttp. setRequestHeader (this. rkeys [I], this. rvalues [I]);
}
}
If (this. Rtype = 'binary '){
This. xhttp. setRequestHeader ("Content-Type", "multipart/form-Data ");
} Else {
This. xhttp. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded ");
}
}; Chinaz.com

// Send data in post Mode
This. sendpost = function (purl ){
VaR pdata = "";
VaR I = 0;
This. State = 0;
This. xhttp. Open ("Post", purl, true );
This. sendhead ();
If (this. keycount! =-1) {// Post Data
For (; I <= This. keycount; I ++ ){
If (pdata = "") pdata = This. Keys [I] + '=' + this. Values [I];
Else pdata + = "&" + this. Keys [I] + '=' + this. Values [I];
}
}
This. xhttp. Send (pdata );
};

[Chinese webmaster site]

 

// Send data in get Mode
This. sendget = function (purl ){
VaR gkey = "";
VaR I = 0;
This. State = 0;
If (this. keycount! =-1) {// get Parameter
For (; I <= This. keycount; I ++ ){
If (gkey = "") gkey = This. Keys [I] + '=' + this. Values [I];
Else gkey + = "&" + this. Keys [I] + '=' + this. Values [I];
}
If (Purl. indexof ('? ') =-1) purl = purl + '? '+ Gkey;
Else purl = purl + '&' + gkey;

[Chinese webmaster site]

}
This. xhttp. Open ("get", purl, true );
This. sendhead ();
This. xhttp. Send ();
}; [Chinese webmaster station]

 

} // End class dedeajax
The above code is saved as: dedeajax. js

[Chinese webmaster site]

 

OK. Now let's do the simplest test.
Test.htm [Chinese webmaster station]

Code: [copy to clipboard] <script language = 'javascript 'src = 'dedeajax. js'> </SCRIPT>
<Script language = 'javascript '>
Function witeok ()
{
VaR myinfo = Document. getelementbyid ("myinfo ");
If (myajax. xhttp. readystate = 4 ){
If (myajax. xhttp. Status = 200 ){
Myinfo. innerhtml = myajax. xhttp. responsetext;
}
}
}
VaR myajax = new dedeajax (witeok );
Myajax. addkey ("key1 ","----------------------------");
Myajax. sendpost ("test. php"); [Chinese webmaster site]

</SCRIPT>

Chinaz.com

 

<Div id = 'myinfo'> <div>
Test. php

Chinaz.com

 

Code: [copy to clipboard] <?
Header ("Content-Type: text/html; charset = gb2312 ");
Echo $ _ post ['key1'];
?>
What have you seen? Don't be excited. What really gives you a headache hasn't come out yet. [Chinese webmaster site]

Put

[Chinese webmaster site]

 

Code: [copy to clipboard] This. addkey = function (skey, svalue ){
This. keycount ++;
This. Keys [This. keycount] = skey;
This. Values [This. keycount] = svalue; // escape (svalue );
};
Escape shielded

Chinaz.com

 

Send
Myajax. addkey ("key1", "----- 中--- --- ---- -----";

[Chinese webmaster site]

 

What did you see? Oh, it's starting to grow.

Chinaz.com

 

Put escape back first
This. Values [This. keycount] = escape (svalue); [Chinese webmaster site]

So what we see is:
----- % U4e2d --- % u56fd ---- % u4eba -----

[Chinese webmaster site]

 

How can we get % u4e2d back? This is a complicated problem for PHP. It is much easier to use ASP.

Chinaz.com

 

The following is a function I wrote: chinaz.com

Code: [copy to clipboard] // Unicode URL encoding to GBK encoding function
Function unicode2gbk ($ Str)
{
// Load the dictionary
If (! Isset ($ globals ['gbkunidic '])
{
$ DS = file ("./data/gbk_unicode.dic ");
Foreach ($ ds as $ L ){
$ Globals ['gbkunidic'] [hexdec ('0x '. substr ($ L,)] = substr ($ L );
}
}
// Process the string
$ Glen = strlen ($ Str );
$ Okstr = "";
For ($ I = 0; $ I <$ Glen; $ I ++)
{
If ($ Glen-$ I> 4 ){
If ($ STR [$ I] = '%' & $ STR [$ I + 1] = 'U') {[Chinese webmaster site]
$ Uni = hexdec ('0x '. substr ($ STR, $ I + 2, 4 ));
If (isset ($ globals ['gbkunidic '] [$ uni]) {
$ Uni = $ globals ['gbkunidic '] [$ uni];
$ Okstr. = CHR (hexdec (substr ($ uni,). CHR (hexdec (substr ($ uni )));
}

Chinaz.com

Else $ okstr. = "& # {". hexdec ("0x". $ Uni ).";";
$ I = $ I + 5;
}
Else $ okstr. = $ STR [$ I];
}
Else $ okstr. = $ STR [$ I];
}
Return $ okstr;
}
Dictionary files: http://www.ce86.com/myimg/data.rar

[Chinese webmaster site]

 

Change the test. php output to [Chinese webmaster site]

Echo unicode2gbk ($ _ post ['key1']);

Chinaz.com

 

It's normal.

[Chinese webmaster site]

 

The following describes the XML-related content [Chinese webmaster site].

Iii. Usage of xmldom
  
This chapter is simpler because it only serves as a lead, because it is for PHP. If Asp.net or JSP is used to write communications involving the Web server class, it's not just about Ajax anymore. The task in this chapter is to use test2.php chinaz.com

Code: [copy to clipboard] <?
Header ("Content-Type: text/XML; charset = gb2312 ");
Echo '<'.'? '. "XML version =/" 1.0/"encoding =/" gb2312 /"".'? '. ">
<Myhome>
<Item sex =/"male/"> I am Xiaoyi </item>
<Item sex =/"female/"> I am a junior </item>
</Myhome>
";
?> This XML document is displayed on the client in its own way. Because xmlis a problem between the East and the West, the syntax is also strict. The source code of the test2.htm page is

Chinaz.com

 

Code: [copy to clipboard] <HTML>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312">
<Title> Ajax test </title>
</Head>
<Body onload = "witeloaddocument ()">
<Script language = 'javascript 'src = 'deajax. js'> </SCRIPT>
<Script language = 'javascript '>
VaR myajax = new dedeajax (witeok );
Function witeok ()
{
VaR myinfo = Document. getelementbyid ("myinfo ");
VaR mydom = NULL;
Myinfo. innerhtml = "The following are the processing results: <br/> ";
If (myajax. xhttp. readystate = 4 ){
Mydom = myajax. xhttp. responsexml;
Alert (mydom );
}
}
Function witeloaddocument ()
{
Myajax. sendget ("test2.php ");
}
</SCRIPT>
<Div id = 'myinfo'> <div>

[Chinese webmaster site]

</Body>
</Html>
Test in IE. If the pop-up dialog box is [object], the returned XML xmldoc is successfully obtained.

[Chinese webmaster site]

 

The processing is as follows:

[Chinese webmaster site]

 

Code: [copy to clipboard] function witeok ()
{
VaR myinfo = Document. getelementbyid ("myinfo ");
VaR mydom = NULL;
Myinfo. innerhtml = "The following are the processing results: <br/> ";
If (myajax. xhttp. readystate = 4 ){
Mydom = myajax. xhttp. responsexml;
VaR nodelist = mydom. selectnodes ("/myhome/item ");
VaR mynode = NULL;
VaR myatt = NULL;
VaR mysex = "";
For (I = 1; I <= nodelist. length; I ++)
{
Mynode = nodelist [I-1];
For (j = 0; j <myinfo. Attributes. length; j ++)
{

Chinaz.com

If (! Mynode. attributes [J]) break;
Myatt = mynode. attributes [J];
If (myatt. Name = 'sex') mysex = myatt. value;
}
Myinfo. innerhtml + = "I am:" + mynode. Text + ", and my gender is:" + mysex + "<br/> ";
}
}
}

Chinaz.com

 

Result: [Chinese webmaster station]

Code: [copy to clipboard] The following is the processing result:
I am: I am Xiaoyi, and my gender is: Male
I am: I am a child, and my gender is: Female
OK, the target has reached chinaz.com

Dom has only been tested in IE6 and may be problematic in Firefox. You may refer to the compatibility documentation. [Chinese webmaster site]

 

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.