A detailed discussion of AJAX applications in WEB2.0

Source: Internet
Author: User
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
Use XHTML and CSS for standardized rendering;
Use DOM for Dynamic Display and interaction;
Use XML and XSLT for data exchange and processing;
Use XMLHttpRequest for asynchronous data reading;
Finally, use JavaScript to bind and process all data;
How does Ajax work? To make user operations asynchronous with server responses. 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 whether a Pass account exists to describe the actual application of AJAX:

(1) return the server response using a text string to verify the existence of the Netease Pass account; 
(2) 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 provide the XMLHttpRequest class, but they have 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 or 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? Create XMLHttpRequest in Safari and other browsers 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 --){
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 );

Is the first parameter of open () the HTTP request method? GET, POST, or any method supported by the server you want to call. 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. Be sure not to write it as FunctionName (). Of course, you can also directly create the 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 {
// Failed to receive the complete Server Response
}

When readyState = 4, a complete server response has been received. Then, the function checks the status value of the HTTP server response. 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 

Example 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:
Http://reg.163.com/register/checkssn.jsp? Username =User Name

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

<Script type = "text/javascript" language = "javascript">
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. getElementById ('163id'). value; // define url parameters
Xmlhttp_request = getXMLRequester (); // call the function for creating XMLHttpRequest
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) {// the HTTP server response value is 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 );
}
}
}
</Script>

Create a text box in the <body> area with the id of 163id

<Input type = "text" id = "163id" onpropertychange = "IDRequest ('Http://reg.163.com/register/checks... me = ') "/> 

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

<Div id = "message"> </div>

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 and find that the detection method of Kingsoft pass username is:
Http://pass.kingsoft.com/ksgweb/jsp/login/uid.jsp? Uid =Username, and XML data is returned:
<? Xml version = "1.0" encoding = "UTF-8" standalone = "yes"?>
<Response>
<Method> isExistedUid </method>
<Result>-2 </result>
</Response>

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 operations on the program language and database, which is not difficult for readers who have a certain program base. This article focuses on the client AJAX application experience, the majority of readers can make a colorful application based on the principles described in this article and various style Expression methods. I hope this article will serve as a reference.

Demo address:

Note: I have uploaded the prepared file to my Blog. You can test the file. Because Ajax and Xmlhttp cannot send cross-origin requests, therefore, adjust the security level of IE during testing or temporarily add xiacong.com to the trusted site.
Netease pass query demo (AJAX ):Http://www.xiacong.com/test/163.htm 
Kingsoft pass query demo (AJAX ):Http://www.xiacong.com/test/j3.htm 

Appendix

(1) status code supported by HTTP 1.1

100 the initial request for Continue has been accepted, and the customer shall Continue to send the rest of the request
101 The Switching Protocols server converts a client-compliant request to another protocol
200 OK everything is normal, and the response document to the GET and POST requests follows.
The 201 Created server has Created a document and the Location header provides its URL.
202 Accepted has Accepted the request, but the processing has not been completed.
203 the Non-Authoritative Information document has been normally returned, but some response headers may be incorrect because the document copy is used.
204 No Content does not have a new document. The browser should continue to display the original document. This status code is useful if the user regularly refreshes the page and the Servlet can determine that the user document is new enough.
205 there is no new Content in the Reset Content, but the browser should Reset the Content displayed by it. Used to force the browser to clear the input content of the form
206 Partial Content the client sent a GET request with the Range header, and the server completed it.
300 the documents requested by the Multiple Choices client can be found in Multiple locations, which are listed in the returned documents. If the server needs to give priority, it should be specified in the Location response header.
301 Moved Permanently the document requested by the customer is elsewhere. The new URL is provided in the Location header and the browser should automatically access the new URL.
302 Found is similar to 301, but the new URL should be treated as a temporary alternative, rather than permanent.
303 See Other is similar to 301/302. The difference is that if the original request is POST, the redirection target document specified by the Location header should be extracted through GET
304 The Not Modified client has a buffered document and issued a conditional request (generally, the If-Modified-Since header is provided to indicate that the customer only wants to update the document on a specified date ). The server tells the customer that the original buffer documentation can still be used.
305 the document requested by the Use Proxy client should be extracted from the Proxy server specified by the Location header
307 Temporary Redirect and 302 (Found) are the same. Many browsers mistakenly respond to the 302 response for redirection. Even if the original request is POST, it can only be redirected when the POST request actually responds to 303. For this reason, HTTP 1.1 adds 307 to clear the region code in several states: When a 303 response occurs, the browser can follow the redirected GET and POST requests; if a 307 response occurs, the browser can only follow the redirection to get requests.
400 syntax error in Bad Request.
401 Unauthorized the customer attempted to access the password-protected page without authorization. The response contains a WWW-Authenticate header. the browser displays the username/password dialog box accordingly, and then sends a request again after entering the appropriate Authorization header.
403 Forbidden resources are unavailable.
404 Not Found cannot find the resource at the specified position
405 Method Not Allowed request methods (GET, POST, HEAD, DELETE, PUT, TRACE, etc.) are Not applicable to specified resources.
406 the resource specified by Not Acceptable has been found, but its MIME type is incompatible with the one specified by the customer in the Accpet header.
407 Proxy Authentication Required is similar to 401, indicating that the customer must first be authorized by the Proxy server.
408 Request Timeout the client has not sent any Request within the waiting time permitted by the server. The customer can repeat the same request later.
409 Conflict is usually related to PUT requests. The request cannot be successful because the request conflicts with the current status of the resource.
410 the document requested by Gone is no longer available, and the server does not know which address to redirect. It differs from 404 in that if 407 is returned, the document permanently leaves the specified position, and 404 indicates that the document is unavailable for unknown reasons.
The 411 Length Required server cannot process the request unless the customer sends a Content-Length header.
412 Precondition Failed: Some of the prerequisites specified in the request header fail.
413 the size of the target Request Entity Too Large document exceeds the size that the server is willing to process. If the server thinks it can process the request later, it should provide a Retry-After Header
414 Request URI Too Long URI is Too Long
416 the Requested Range Not Satisfiable server cannot meet the Range header specified by the customer in the request.
500 the Internal Server Error Server encounters unexpected circumstances and cannot complete the customer's request
501 The Not Implemented server does Not support the functions required to implement the request. For example, the customer sends a PUT request not supported by the server.
502 when the Bad Gateway server acts as a Gateway or proxy, in order to complete the request to access the next server, but the server returns an INVALID RESPONSE
503 the Service Unavailable server fails to respond due to maintenance or overload. For example, Servlet may return 503 when the database connection pool is full. A Retry-After header can be provided when the server returns 503
504 Gateway Timeout is used by a proxy or Gateway server, indicating that the remote server cannot receive a response in a timely manner.
505 the HTTP Version Not Supported server does Not support the HTTP Version specified in the request

(2) XMLHttpRequest object Method

Abort () stops the current request
GetAllResponseHeaders () is used as a string to return to the complete headers.
GetResponseHeader ("headerLabel") returns a single header label as a string
Open ("method", "URL" [, asyncFlag [, "userName" [, "password"]) sets the target URL, method, and other parameters of a pending request.
Send (content) send request
SetRequestHeader ("label", "value") sets the header and sends it together with the request

(3) XMLHttpRequest object attributes

Onreadystatechange event trigger
ReadyState object status (integer ):
0 = not initialized
1 = reading
2 = read
3 = interaction in progress
4 = complete
The text version of the data returned by the responseText server process
ResponseXML: XML Document Object compatible with DOM returned by the server process
Status Code returned by the status server, for example, 404 = "found at the end of the file", 200 = "successful"
Status text returned by the statusText Server

 

ZT: http://www.xiacong.com/blogview.asp? LogID = 305

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.