A detailed explanation of AJAX application in Web2.0

Source: Internet
Author: User
Tags define object functions header http request string versions window
ajax|web|web2| detailed

The recent hot topic on the Internet is of course about the application of WEB2.0, where Ajax is one of the core of WEB2.0.

Ajax is the abbreviation for asynchronous JavaScript and XML. It's not a new language or technology, it is actually a number of techniques that are combined in a certain way to play their part in a collaborative collaboration that includes standardizing rendering using XHTML and CSS, using DOM for dynamic display and interaction, and data exchange and processing using XML and XSLT; Asynchronous data reads are performed using XMLHttpRequest, and all data is finally bound and processed with JavaScript.

Ajax works by adding a middle tier between the user and the server, enabling the user to respond asynchronously to the server. In this way, some of the previous server burden of work to the client, the client idle processing capacity to deal with, reduce the burden of server and bandwidth, so as to save the ISP space and bandwidth rental costs.

We have two verification pass account is the existence of an example to describe the application of Ajax in practice: A text string to return the response of the server to verify the existence of NetEase pass account, the XmlDocument object method to return the response to verify the existence of Jinshan pass account.

First, we need JavaScript to create the XMLHttpRequest class to send an HTTP request to the server, the XMLHttpRequest class is first introduced by Internet Explorer as an ActiveX object, known as XMLHTTP. Later Mozilla﹑netscape﹑safari and other browsers also provided XMLHttpRequest classes, but they created different methods of XMLHttpRequest classes.

For Internet Explorer browsers, create the XMLHttpRequest method as follows:



Xmlhttp_request = new ActiveXObject ("Msxml2.xmlhttp");

Xmlhttp_request = new ActiveXObject ("Microsoft.XMLHTTP");

Because the XMLHTTP version may not be consistent in different Internet Explorer browsers, for better compatibility with different versions of Internet Explorer browsers, we need to base different versions of the Internet Explorer browser to create the XMLHttpRequest class, the code above is a way to create XMLHttpRequest classes based on different Internet Explorer browsers.

For browsers such as Mozilla﹑netscape﹑safari, the XMLHttpRequest method is created as follows: Xmlhttp_request = new XMLHttpRequest ();

If the server's response does not have an XML Mime-type header, some Mozilla browsers may not work correctly. To solve this problem, if the header of the server response is not text/xml, other methods can be invoked to modify the header.

Xmlhttp_request = new XMLHttpRequest ();

Xmlhttp_request.overridemimetype (' Text/xml ');

In practical applications, in order to be compatible with many different versions of browsers, the method of creating the XMLHttpRequest class is generally written as follows:

 

Try

{

if window. ActiveXObject)

{

for (var i = 5; I i--)

{

try

{

if (i = 2)

{
Br>xmlhttp_request = new ActiveXObject ("Microsoft.XMLHTTP");

}

Else

{

Xmlhttp_request = new ActiveXObject ("msxml2.xmlhttp." + i + ". 0");

}

Xmlhttp_request.setrequestheader ("Content-type", "Text/xml");

Xmlhttp_request.setrequestheader ("Content-type", "gb2312"); break;

}

catch (E)

{

Xmlhttp_request = false;

}

}

}

Else if window. XMLHttpRequest)

{

Xmlhttp_request = new XMLHttpRequest ();

if (xmlhttp_request.overridemimetype)

{

Xmlhttp_request.overridemimetype (' text/xml ');

}

{

}

catch (E)

{

Xmlhttp_request = false;

}

After you have defined how to handle the response, you send the request. You can call the open () and send () methods of the HTTP request class, as follows:

Xmlhttp_request.open (' Get ', URL, true);

Xmlhttp_request.send (NULL);

The first parameter of open () is the way the HTTP request-get,post or any server supports that you want to invoke. This argument is capitalized according to the HTTP specification, otherwise some browsers, such as Firefox, may not be able to process the request.

The second parameter is the URL of the request page.

The third parameter sets whether the request is asynchronous mode. If the True,javascript function continues to execute without waiting for the server to respond. This is "A" in "AJAX".

After using JavaScript to create a XMLHttpRequest class to send an HTTP request to the server, decide what to do when you receive a response from the server. This tells the HTTP request object which JavaScript function to use to handle the response. You can set the object's onReadyStateChange property to the function name of the JavaScript you want to use, as follows: Xmlhttp_request.onreadystatechange =functionname;

FunctionName is a function name created with JavaScript, be careful not to write functionname (), of course, we can also create JavaScript code directly after onreadystatechange, for example: XMLHTTP_ Request.onreadystatechange = function () {

JavaScript Code Snippets

};

In this function. You first check the status of the request. The function can handle the response only if a full server response has been received. XMLHttpRequest provides a ReadyState property to determine the server response.

The value of readystate is as follows;

0 (uninitialized)

1 (loading)

2 (Load complete)

3 (in interaction)

4 (complete)

So only when readystate=4, a full server response has been received, can the function handle the response. The specific code is as follows:

if (http_request.readystate = = 4) {//Received full server response} else {//not received full server response} When readystate=4, a full server response has been received, and then the function checks the HTTP server The status value of the response. Full state values can be found in the documentation for the document. When the HTTP server responds with a value of 200, it indicates that the status is normal.

After checking the status value of the request and the HTTP status value of the response, you can process the data obtained from the server. There are two ways to get this data:

(1) Returns the response of the server as a text string

(2) Return response in XmlDocument object mode

Instance one, returns the server's response with the text string method to verify the NetEase pass account existence

First, we login NetEase pass registration page, you can see the detection of the existence of the user name is the user name submitted to the CHECKSSN.JSP page to judge, the format is:

Reg.163.com/register/checkssn.jsp?username= Username According to the method mentioned above, we can use AJAX technology to detect NetEase pass user name:

First step: Create a new Web page based on XHTML standards, insert JavaScript functions into the region as follows:

function Getxmlrequester ()

{var xmlhttp_request = false; try

{if (window. ActiveXObject)

{for (var i = 5; i; i--) {try{if (i = = 2)

{xmlhttp_request = new ActiveXObject ("Microsoft.XMLHTTP");}

Else

{xmlhttp_request = new ActiveXObject

("msxml2.xmlhttp." + i + ". 0");

Xmlhttp_request.setrequestheader

("Content-type", "Text/xml");

Xmlhttp_request.setrequestheader ("Content-type", "gb2312"); }

break;

catch (e) {xmlhttp_request = false;}} }

else if (window. XMLHttpRequest)

{xmlhttp_request = new XMLHttpRequest ();

if (Xmlhttp_request.overridemimetype)

{xmlhttp_request.overridemimetype (' text/xml ');} } }

catch (e) {xmlhttp_request = false;}

return xmlhttp_request; }

function Idrequest (n)

{//define JavaScript functions to be executed after receiving the response from the server

Url=n+document.getelementbyi (' 163id '). Value;

Define URL parameter Xmlhttp_request=getxmlrequester ();

Call to create XMLHttpRequest function xmlhttp_request.onreadystatechange = docontents;

Call docontents function Xmlhttp_request.open (' Get ', url, true);

Xmlhttp_request.send (NULL); }function docontents ()

{if (xmlhttp_request.readystate = 4)

{//Receive Full server response if (Xmlhttp_request.status = 200) {

HTTP Server response value OK document.getElementById (' message '). InnerHTML

= Xmlhttp_request.responsetext;

Writes the string returned by the server to the area with the ID message in the page}

else {alert (http_request.status);}} }

Create a text box in the area with an ID of 163id

Another blank area with an ID of messsge is used to display the return string (or to intercept a portion of the string display via a JavaScript function):

In this way, an AJAX-based user name Detection page is done, but this page will return the server response to generate all the strings of the page, of course, can also do some operations on the returned string, easy to apply to different needs.

Example two, the XmlDocument object Way returns the response to verify that Jinshan Pass account exists

In the example above, when the server's response to the HTTP request is received, we invoke the Reponsetext attribute of the requested object. This property contains the contents of the server return response file. Now we return the response as a XmlDocument object, where the Reponsetext property is no longer needed and the Responsexml property is used.

First landed Jinshan Pass registration page, we found Jinshan Pass user name detection method is: pass.kingsoft.com/ksgweb/jsp/login/uid.jsp?uid= username, and return the XML data:

IsExistedUid-2

When the result value is-1, the user name is registered, and when the result value is 2, the user name has not been registered, so it is possible to know whether the user name is registered by the judgment of the value.

To modify the previous example code:

First find

= Xmlhttp_request.responsetext;

To

var response = Xmlhttp_request.responseXML.documentElement;

var result = response.getelementsbytagname (' result ') [0].firstchild.data;

Return result node data

if (Result ==-2) {

document.getElementById (' message '). InnerHTML =

"Username" +document.getelementbyid (' 163id '). value+ "not registered";

else if (result ==-1) {

"Sorry, username" +document.getelementbyid (' 163id '). value+ "already registered";}

Through the above two examples to illustrate the AJAX client base application, the use of NetEase and Jinshan off-the-shelf server program, of course, in order to develop a suitable page of the program, but also need to write their own server program, which design to the program language and database operation, It must not be difficult for a reader to have a certain program base.

Demo Address:

Description: Has been made a good file uploaded to my blog, you can test, because Ajax and XMLHTTP can not cross domain request, so the test please adjust IE security level or will xiacong.com temporarily joined the trust site.

NetEase Pass Query Demo (AJAX): www.xiacong.com/test/163.htm

Jinshan Pass Query Demo (AJAX): www.xiacong.com/test/j3.htm

Edit tips: More Ajax content, please go to the AJAX Development application column

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.