Proficient in Ajax technology

Source: Internet
Author: User
Tags add array object chr header http request net php example


Ajax this name how to come, I also can not, presumably (Active Javascript Action Xml) bar, white point is the use of Javascript, XMLHTTP and XMLDOM technology and Web site to deal with the user some of the operation of the method bar.

Then I will be three steps to explain how to use Ajax technology to do development.

A. Manipulate XMLHTTP objects with JavaScript

Second, the server department response to the XMLHTTP request (php example)

Three, the use method of XMLDOM

First part:

A. Manipulate XMLHTTP objects with JavaScript

IE7, Mozilla, Firefox and other browsers, JavaScript is built-in XMLHttpRequest this object, but ie5+ does not, you need to use the following methods to start:
IE 6
try{xhttp = new ActiveXObject ("Msxml2.xmlhttp";} catch (E) {;}
ie5+
if (xhttp = = null) try {xhttp = new ActiveXObject ("Microsoft.XMLHTTP";} catch (E) {;}

Consider the compatibility of different browsers, start a XMLHTTP generally should be in the following way:

Code:[copy to Clipboard]var xhttp = null;

if (window. XMLHttpRequest) {//ie7, Mozilla, Firefox and other browsers built this object

Xhttp = new XMLHttpRequest ();

}else if (window. ActiveXObject) {//ie6, IE5

try{xhttp = new ActiveXObject ("Msxml2.xmlhttp");} catch (E) {;}

if (xhttp = = null) try {xhttp = new ActiveXObject ("Microsoft.XMLHTTP");} catch (E) {;}

}

For the use of XMLHTTP, the following order is generally observed:

1, initialize the XMLHTTP object (above);

2, open the link

Method

Xhttp.open ("Get", purl, True);

Parameter one: Send data with Get or POST

Parameter two, request URL (can only request resources on your server, general browser security restrictions can not read cross-domain data)

A parameter of three or True indicates an asynchronous transfer (you can do something else before the server returns information is complete), and False indicates the transmission of the blocking mode.

3, set the HTTP request header to send

Method:

Xhttp.setrequestheader (Key,value);

In general, the default to send the head is: Xhttp.setrequestheader ("Content-type", "application/x-www-form-urlencoded";

This means that the request headers of the type of content being sent are used to send text data, and JavaScript is sent by default in Unicode, and another form is: Xhttp.setrequestheader ("Content-type", "multipart/ Form-data "; This means sending binary forms of data, which, for security reasons, are generally not used to send data in this way, so this is generally useless.

If your site is open to use the refer parameter to the anti-theft chain, then you must use this method to specify the refer parameter, or if the user needs to log in to do an operation, then specify the Cookie's request header.

4. Send data

Methods: Xhttp.send (PostData);

For the use of get tapping requests, do not need to specify postdata, directly in the form of Test.php?a=a&b=b URL to request.

In the case of post, you need to use the form of key1=value2&key2=value2 to process the data, merge it in the PostData string, and then send it.

Precautions:

JavaScript sends data by default in Unicode, processing the returned data must be in utf-8 format, so when sending, you need to use the escape () function to handle the value of PostData and URLs, you must restore these value on the server, And the Unicode to the page encoding value, so if you use JSP or asp.net will be simpler, but if the use of PHP to deal with what is laborious, and so will teach you how to do.

5, confirm the server return information complete download

[1] If the request is sent in a blocking manner, then the direct use of if (xhttp.readystate = = 4) can be used to determine whether or not to complete.

The specific property values for the readyState are:
0 No Open
1 not send.
2 Status Unknown
3 is transmitting.
4 Transmission Complete

Of course, in order to safeguard the sake, but also need to add one more judgment, is if (xhttp.status = =), status is the HTTP protocol in the return header code

1xx (alas, forgotten)
2XX indicates success information
3XX represents page Transfer
4xx page does not exist
5XX indicates various errors on the server

If your page does not have special handling, generally use if (xhttp.status = = 200) To make sure that the content is returned correctly

[2] If you use asynchronous transmission, you need to use the onReadyStateChange event to monitor

Xhttp.onreadystatechange = function ()
{
Here to make a decision on the blocking mode above.
if (myajax.xhttp.readyState = = 4) {
if (Myajax.xhttp.status = = 200) {
Subsequent actions to take
}
}
}

6. Get return result

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

of which 1, 2 are binary way, generally rarely used, 4 do not see all know

If there is no accident on the service side [3] returns a Xmldom object

Second, the server department response to the XMLHTTP request (php example)

To simplify operations, encapsulate the XMLHTTP operations here as a class

Code:[copy to Clipboard]function Dedeajax (witeokfunc) {//witeokfunc is an asynchronous state event handler

XMLHTTP and XMLDOM objects
This.xhttp = null;
This.xdom = null;

A key value pair for post or get send data
This.keys = Array ();
This.values = Array ();
This.keycount =-1;

HTTP request Headers
This.rkeys = Array ();
This.rvalues = Array ();
This.rkeycount =-1;
Request Header Type
This.rtype = ' text ';

Initialize XMLHTTP
if (window. XMLHttpRequest) {//ie7, Mozilla, Firefox and other browsers built this object
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, ResponseText

The following is a member function
//--------------------------------

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;
};

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);
};

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;
};

Clears the hash table parameter for the current object
This. Clearset = function () {
This.keycount =-1;
This.keys = Array ();
This.values = Array ();
This.rkeycount =-1;
This.rkeys = Array ();
This.rvalues = Array ();
};

//Send HTTP request headers
this. Sendhead = function () {
        if (this.rkeycount!=-1) {//Send user-set request headers
          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 ");
 }
};

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);
};

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;
}
This.xhttp.open ("Get", purl, True);
This. Sendhead ();
This.xhttp.send ();
};

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

OK, now, let's do the simplest test.
Test.htm

Code:[copy to Clipboard]


test.php


Code:[copy to Clipboard]Header ("content-type:text/html; charset=gb2312 ");
echo $_post[' Key1 '];
?>
What did you see? Don't get excited, the thing that really makes you headache hasn't come out yet.

Put the inside of the class

Code:[copy to Clipboard]this. Addkey = function (skey,svalue) {
this.keycount++;
This.keys[this.keycount] = Skey;
This.values[this.keycount] = Svalue;//escape (svalue);
};
Escape to block out

Send
Myajax. Addkey ("Key1", "-----of----people in---countries of the-----";

What did you see, garbled? Oh, this time the beginning of the big

Put the escape back first.
This.values[this.keycount] = Escape (svalue);

That's what you see.
-----%u4e2d---%u56fd----%u4eba-----

How to get%u4e2d these things back? This is a very complex problem for PHP, and it's a lot easier if you use ASP.

Here's a function I wrote:


code:[copy to clipboard]//unicode URL encoding GBK encoding function
function UNICODE2GBK ($STR)
{
Load a control dictionary
if (!isset ($GLOBALS [' gbkunidic '])
{
$ds = File ("./data/gbk_unicode.dic");
foreach ($ds as $l) {
$GLOBALS [' Gbkunidic '][hexdec (' 0x '. substr ($l, 0,4))] = substr ($l, 5,4);
}
}
Handling strings
$glen = strlen ($STR);
$okstr = "";
for ($i =0; $i < $glen; $i + +)
{
if ($glen-$i > 4) {
if ($str [$i]== '% ' && $str [$i +1]== ' u ') {
$uni = Hexdec (' 0x '. substr ($str, $i +2,4));
if (Isset ($GLOBALS [' gbkunidic '] [$uni])) {
$uni = $GLOBALS [' Gbkunidic '] [$uni];
$okstr. = Chr (Hexdec (substr ($uni, 0,2))). Chr (Hexdec (substr ($uni, 2,2));
}
else $okstr. = "&#{". Hexdec ("0x". $uni). ";";
$i = $i +5;
}
else $okstr. = $str [$i];
}
else $okstr. = $str [$i];
}
return $okstr;
}
Dictionary file: Http://www.ce86.com/myimg/data.rar


Change the test.php output to

echo unicode2gbk ($_post[' key1 '));

It's normal.

Here's something about XML that follows

Three, the use method of XMLDOM
  
Because this article is only the role of lead wire, this chapter is simpler, because for PHP, if the asp.net or JSP to write about the Web server class communication, is not simply Ajax problem, the task of this chapter is to put the test2.php

Code:[copy to Clipboard]Header ("Content-type:text/xml; charset=gb2312 ");
Echo ' < '. '. ' XML version=\ "1.0\" encoding=\ "gb2312\" "." >

I am a small one
I am small two

";
?> This XML document is presented to the client in its own way. Because XML this kind of thing is more troublesome, so the grammar also must be strict, test2.htm the source of the page is

Code:[copy to Clipboard]

   var mydom = null;
   myinfo.innerhtml = "The following is the processing result:
";
   if (myajax.xhttp.readyState = 4) {
     mydom = myajax.xhttp.responseXml;
     alert (mydom);
  }
}
Function witeloaddocument ()
{
   myajax. Sendget ("test2.php");       
}




Test in IE if the pop-up dialog box is [Object] that represents the xmldoc of the returned XML successfully.

The following is the process:

Code:[copy to Clipboard]function Witeok ()
{
var MyInfo = document.getElementById ("MyInfo");
var mydom = null;
myinfo.innerhtml = "The following is the processing result:
";
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++)
{
if (!mynode.attributes[j]) break;
Myatt = Mynode.attributes[j];
if (myatt.name== ' sex ') mysex = Myatt.value;
}
myinfo.innerhtml = "I am:" +mynode.text+ ", My gender is:" + mysex + "
";
}
}
}

Results:

Code:[copy to Clipboard] The following is the processing result:
I am: I am small one, my sex is: male
I am: I am xiao er, my gender is: female
OK, the purpose has been reached

Part of the DOM is only tested in IE6 and may be problematic in Firefox, and you may refer to compatibility-related documentation.



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.