Ajax Learning (iii) Five-step use of--xmlhttprequest objects

Source: Internet
Author: User

The core technology of Ajax is the XMLHttpRequest object, which enables the partial update of a Web page without submitting the entire page to the server. With this object, Ajax can exchange data layers with the server just like a desktop application, rather than having to refresh the interface every time and do not have to hand over the data to the server every time. This reduces the burden on the server and improves responsiveness, and shortens the user's waiting time. Usually an AJAX implementation process has five steps, below our blog in the small example of the example to step through the learning.

1. Create a XMLHttpRequest object.

IE Browser implements XMLHttpRequest as an ActiveX object, and other browsers such as Firefox,opera,netscape implement it as a native JavaScript object, and both versions of IE7.0 and above are support .

 Defines a variable var xmlHttp = null for user-stored XMLHttpRequest objects; Create XMLHttpRequest Object function Creatxmlhttp () {//Determine if the browser supports ActiveX controls, for IE6 and previous versions if (win Dow. ActiveXObject) {//Put all possible activexobject versions in an array var arrxmlhttptypes = [' Micros Oft. XMLHTTP ', ' MSXML2. xmlhttp.6.0 ', ' MSXML2. xmlhttp.5.0 ', ' MSXML2. xmlhttp.4.0 ', ' MSXML2. xmlhttp.3.0 ', ' MSXML2.                XMLHTTP '];                    Create a XMLHttpRequest object for (Var i=0;i<arrxmlhttptypes.length;i++) by looping { try {//create XMLHttpRequest Object xmlHttp = new ActiveXObject (AR                        Rxmlhttptypes[i]);                    If the XMLHttpRequest object is created successfully, jump out of the loop break;                 } catch (ex) {//If creation is unsuccessful, remove the next version from the array to continue creating} }}//Determine if the browser will xmlhttprequesT as a local object implementation, for IE7 and above, Firefox,opera and other browser else if (window.            XMLHttpRequest) {xmlHttp = new XMLHttpRequest (); }        }

  Create the XMLHttpRequest object, call the previously defined function            creatxmlhttp ();            if (xmlhttp!=null)            {                //create a function that responds to XMLHttpRequest object state Change/                               /create HTTP request                               //Send HTTP request                            }            else            {                alert ("Your browser does not support XMLHTTP");            }
2. Register the callback function.
   Create a function that responds to XMLHttpRequest object state changes                Xmlhttp.onreadystatechange = Httpstatechange;
When called asynchronously, the XMLHttpRequest object has several different states that represent the process of an asynchronous invocation.
0: Uninitialized state, just created a XMLHttpRequest object;
1: Initialization state, that is, the XMLHttpRequest object has obtained the data to send to which server, in what way to send information;
2: Send status, XMLHttpRequest start to send data;
3: Data transfer status, at this time XMLHttpRequest is accepting the data returned from the server side, but the data has not been transmitted;
4: Completion status: At this point the XMLHttpRequest object has accepted the data returned from the server side.

Using the onreadystatechange property of the XMLHttpRequest object, you can set a function that responds to XMLHttpRequest object state changes.

When setting a callback function, do not add parentheses after the function name. Parentheses indicate that the return value of the callback function is registered to the onReadyStateChange property.

3. Use the Open method to set up basic information for server-side interaction.
Create HTTP request                Xmlhttp.open ("Get", "UserName.txt", true);
the XMLHttpRequest open(Method,url,flag,name,password) method is used to initialize the object, and the following three parameters are optional. Method: Specifies the way to send HTTP requests to the server, with the parameter values Get,post,head,put and delete five. URL: Specifies the URL of the server, which is the URL of the program that the user processes and returns data from. The URL can be an absolute address or a relative address. Flag: Specifies how HTTP requests are committed, true refers to asynchronous mode, and false refers to synchronous mode. name and password: If the server needs authentication, these two parameters are used to submit the user name and password.

4. Set the data sent to start and server-side interaction.

  Send HTTP request                xmlhttp.send (NULL);

send HTTP request using the send(data) method of the XMLHttpRequest , the data parameter is the parameter passed to the file specified by the URL parameter in the open () method. If you want to pass multiple arguments, separate with "&", you do not need to pass the parameter write "null".


5. In the callback function to determine whether the interaction ends, the response is correct, and as necessary to obtain the server-side returned data, update the page content.

1) Determine if the asynchronous call was successful:

if (xmlhttp.readystate==4)//Asynchronous call completed {      if (xmlhttp.status==200 | | xmlhttp.status==0)//Asynchronous Call succeeded | | Debug      {}} on this                           machine
The readystate property value is 4, which indicates that the asynchronous call is complete, but does not represent a successful execution of the asynchronous call. The status property of the XMLHttpRequest can be obtained from the server to return the state code. 0 represents an incomprehensible HTTP state that is typically returned only when the local computer opens the file. The more commonly used HTTP status code has the following three:

$: The server successfully returned to the Web page.

404: The page requested by the client does not exist.

503: Server response timed out.


2) Get the data returned by the server:

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" ><strong> var userNames = xmlhttp.responsetext;</strong></span>

The ultimate purpose of an asynchronous call is to receive the data returned from the server and determine how to display it in the client page based on that data. After the asynchronous call succeeds, the XMLHttpRequest object obtains the data returned by the server by using the following 4 properties.

responsetext: Indicates that the data returned by the server is returned as a string.

Responsexml: The representation is returned as XML.

Responsebody: Represents the return as a unsigned byte array.

Responsestream: The representation is returned as a IStream object.


3) Local Update:

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" ><strong>//Find the node that is used to display prompt information var node = document.getElementById ("mydiv");//Update Data                   Node.firstChild.nodeValue = text;</strong></span>

After getting the data returned by the server, it will be displayed. Ajax uses the DOM to perform partial update data.

in the Ajax programming can not be separated from the use of XMLHttpRequest objects, each use is to do this five-step work. We'll find a way to deal with the repetitive things. Since this programming step is now well encapsulated, the code is reusable and simplifies programming. But to be a good programmer, it is necessary to understand these five steps.






Ajax Learning (iii) Five-step use of--xmlhttprequest objects

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.