Details about Ajax applications in Web2.0

Source: Internet
Author: User
Details about Ajax applications in Web2.0
[Guide] This article uses two examples to verify the existence of a pass account to describe Ajax in practice: return a server response using a text string to verify the existence of a Netease Pass account; return a response as an xmldocument object to verify whether the Kingsoft Pass account exists.
 

 

Recently, the hot topic on the internet is of course about the application of Web2.0, among which Ajax is one of the core of Web2.0.

Ajax is short for Asynchronous JavaScript and XML. It is not a new language or technology. It is actually a combination of several technologies to play their respective roles in the collaboration of the same community. It includes: standard presentation using XHTML and CSS; Dynamic Display and Interaction Using Dom; data exchange and processing using XML and XSLT; Asynchronous Data Reading using XMLHttpRequest; finally, use JavaScript to bind and process all data.

The working principle of AJAX is equivalent to adding an intermediate layer between the user and the server, so that user operations and server responses are asynchronous. In this way, the previous server workload is transferred to the client, which facilitates the idle processing capability of the client to reduce the burden on the server and bandwidth, this saves ISP space and bandwidth rental costs.

We use two examples to verify the existence of a pass account to describe the actual application of Ajax: return the server response using a text string to verify the existence of a Netease Pass account; return a response as an xmldocument object to verify whether the Kingsoft Pass account exists.

First, we need to use 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, called XMLHTTP. Later, Mozilla, Netscape, Safari, and other browsers also provided the XMLHttpRequest class, but they had different methods to create the XMLHttpRequest class.

For Internet Explorer, the method for creating XMLHttpRequest is as follows:

Xmlhttp_request = new activexobject ("msxml2.xmlhttp. 3.0 ");

// 3.0, 4.0, 5.0

Xmlhttp_request = new activexobject ("msxml2.xmlhttp ");

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

XMLHTTP versions may be different in different Internet Explorer browsers. To better be compatible with different versions of Internet Explorer browsers, we need to create the XMLHttpRequest class based on different versions of Internet Explorer browsers, the above Code creates an XMLHttpRequest Class Based on Different Internet Explorer browsers.

For Mozilla, Netscape, Safari, and other browsers, the XMLHttpRequest method is as follows: xmlhttp_request = new XMLHttpRequest ();

Some Mozilla browsers may not work properly if the server's response does not contain the XML mime-type header. To solve this problem, if the server response header is not text/XML, you can call other methods to modify the header.

Xmlhttp_request = new XMLHttpRequest ();

Xmlhttp_request.overridemimetype ('text/xml ');

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

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; 

After defining how to handle the response, you need to 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 HTTP Request Method-Get, post, or the method you want to call supported by any server. According to HTTP specifications, this parameter must be capitalized; otherwise, Some browsers (such as Firefox) may not be able to process requests.

The second parameter is the URL of the Request page.

The third parameter sets whether the request is in asynchronous mode. If it is true, the JavaScript function will continue to be executed without waiting for the server to respond. This is "A" in "ajax ".

After using JavaScript to create an XMLHttpRequest class to send an HTTP request to the server, you need to decide what to do when the server receives the response. This tells the HTTP request object which JavaScript function is used to process the response. You can set the onreadystatechange attribute of the object to the name of the JavaScript function to be used, as shown below: xmlhttp_request.onreadystatechange = functionname;

Functionname is the name of the function created with JavaScript. Do not write it as functionname (). Of course, you can also directly create javascript code after onreadystatechange, for example, xmlhttp_request.onreadystatechange = function (){

// JavaScript code segment

};

In this function. First, check the Request status. Only when a complete server response has been received can the function process the response. XMLHttpRequest provides the readystate attribute to determine the server response.

The value of readystate is as follows;

0 (not initialized)

1 (loading)

2 (loaded)

3 (in interaction)

4 (finished)

So only when readystate = 4, a complete server response has been received can the function process the response. The Code is as follows:

If (http_request.readystate = 4) {// receives the complete Server Response} else {// does not receive the complete Server Response} When readystate = 4, A complete server response has been received. Then, the function checks the HTTP server response status. For complete status values, see W3C documentation. When the HTTP server response value is 200, the status is normal.

After checking the Request status value and response HTTP status value, you can process the data obtained from the server. There are two ways to obtain the data:

(1) return the server response in the form of a text string

(2) return a response as an xmldocument object

Instance 1: return the server response using a text string to verify the existence of the Netease Pass account

First, log on to the Netease pass registration page and check whether the user name exists. Submit the user name to the checkssn. jsp page for determination. The format is:

Reg.163.com/register/checkssn.jsp? Username = username based on the method described above, we can use Ajax technology to detect Netease pass usernames:

Step 1: create a web page based on the XHTML standard and insert the JavaScript function in the area as follows:

Function getxmlrequester ()

{Var xmlhttp_request = false; try

{If (window. activexobject)

{For (VAR I = 5; 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)

{// Defines the JavaScript function to be executed after receiving the Server Response

Url = N + document. getelementbyi ('163id'). value;

// Define the URL parameter xmlhttp_request = getxmlrequester ();

// Call the XMLHttpRequest function xmlhttp_request.onreadystatechange = docontents;

// Call the docontents function xmlhttp_request.open ('get', URL, true );

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

{If (xmlhttp_request.readystate = 4)

{// Receives the complete server response if (xmlhttp_request.status = 200 ){

// HTTP server response value: OK document. getelementbyid ('message'). innerhtml

= Xmlhttp_request.responsetext;

// Write the string returned by the server to the region where the ID is message on the page}

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

Create a text box in the region with the ID 163id

Create a blank area with ID messsge to display the returned string (you can also use the JavaScript function to capture some strings for display ):

In this way, a user name detection Page Based on AJAX technology is ready, but this page will return all the strings on the page generated by the server response. Of course, you can also perform some operations on the returned strings, it is easy to apply to different needs.

Example 2: return a response as an xmldocument object to verify the existence of the Kingsoft Pass account

In the above example, when the server receives the response to the HTTP request, we will call the reponsetext attribute of the request object. This attribute contains the content of the response file returned by the server. Now we return a response in the form of an xmldocument object. At this time, the responsexml attribute is no longer required for the reponsetext attribute.

First, log on to the Kingsoft pass registration page. We found that the Kingsoft pass user name is detected in pass.kingsoft.com/ksgweb/jsp/login/uid.jsp? Uid = username, and XML data is returned:

Isexisteduid-2

If the result value is-1, it indicates that the user name has been registered. If the result value is-2, it indicates that the user name has not been registered, therefore, you can determine whether the user name is registered by checking the result value.

Modify the code of the previous example:

First find

document.getElementById('message').innerHTML 

= xmlhttp_request.responseText;

Changed:

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 ){

Document. getelementbyid ('message'). innerhtml =

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

The above two examples illustrate the basic Ajax client applications, using Netease And Kingsoft ready-made server-side programs. Of course, to develop programs suitable for your own pages, you also need to write your own server-side programs, this design involves the operation of the program language and database, which is not very difficult for readers who have a certain program base.

 

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.