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;
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 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 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 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.CodeIt is the method for creating the XMLHttpRequest Class Based on Different Internet Explorer browsers.

For Mozilla, Netscape, Safari, and other browsers, the method for creating XMLHttpRequest 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 --) {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) {response ('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. 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 {// does not 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:
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) {response ('text/xml') ;}} catch (e) {xmlhttp_request = false ;} return xmlhttp_request;} function idrequest (n) {// defines the JavaScript function URL to be executed after receiving the server response = N + document. getelementbyid ('163id '). value; // define the URL parameter xmlhttp_request = getxmlrequester (); // call the function handler that creates XMLHttpRequest = 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) {// value of the HTTP server response okdocument. 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/checkssn.jsp? Username = ') "/>

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:
Pass.kingsoft.com/ksgweb/jsp/login/uid.jsp? Uid = username, and XML is returnedData:

<? 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 application of Ajax client, using Netease And Kingsoft ready-made ServerProgramOf course, in order to develop a program suitable for your own page, you also need to write your own server-side program, which is designed to operate the program language and database, this article focuses on the Application Experience of client-side Ajax, 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:

Netease pass query demo (Ajax ):Www.xiacong.com/test/163.htm
Kingsoft pass query demo (Ajax ):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 () as the string to return the complete headersgetresponseheader ("headerlabel") as the string to return a single header tag open ("method", "url "[, asyncflag [, "username" [, "password"]) sets the target URL, method, and other parameters of the pending request to send the request setRequestHeader ("label ", "value") sets the header and sends it together with the request

(3) XMLHTTPRequest object attributes

 
Onreadystatechange event trigger readystate object state (integer ): 0 = not initialized 1 = reading in progress 2 = read 3 = interaction in progress 4 = completion of responsetext server process returned Data Text Version responsexml server process returned data compatible Dom XML Document Object status status Code returned by the server, for example: 404 = "found at the end of the file", 200 = "successful" statustext server returned status text information
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.