Ajax Learning (iii) -- use the XMLHttpRequest object in five steps: ajaxxmlhttprequest

Source: Internet
Author: User

Ajax Learning (iii) -- use the XMLHttpRequest object in five steps: ajaxxmlhttprequest

The core technology of Ajax is the XMLHttpRequest object. It can update webpages without submitting the entire page to the server. With this object, Ajax can exchange data layers with the server just like a desktop application, without refreshing the interface every time, or having to submit the data processing work to the server every time. This reduces the load on the server, increases the response speed, and shortens the user's waiting time. Generally, there are five steps to implement Ajax. The following is an example of a small instance in our blog.

1. Create an XMLHttpRequest object.

IE implements XMLHttpRequest as an ActiveX object. other browsers, such as Firefox, Opera, and Netscape, implement XMLHttpRequest as a local javascript Object. Both methods of creating IE7.0 and later versions are supported.Supported.

// Define the variable var xmlHttp = null for storing the XMLHttpRequest object; // create the XMLHttpRequest object function creatXMLHTTP () {// determine whether the browser supports ActiveX controls, for IE6 and earlier versions of if (window. activeXObject) {// put all possible versions of ActiveXObject in an array var arrXmlHttpTypes = ['Microsoft. XMLHTTP ', 'msxml2. XMLHTTP.6.0 ', 'msxml2. XMLHTTP.5.0 ', 'msxml2. XMLHTTP.4.0 ', 'msxml2. XMLHTTP.3.0 ', 'msxml2. XMLHTTP ']; // create the XMLHttpRequest object for (var I = 0; I <arrXmlHttpTypes. length; I ++) {try {// create the XMLHttpRequest object xmlHttp = new ActiveXObject (arrXmlHttpTypes [I]); // If the XMLHttpRequest object is created successfully, the loop break exists ;} catch (ex) {// if the file cannot be created successfully, extract the next version from the array and create another version }}// determine whether the browser implements XMLHttpRequest as a local object, else if (window. XMLHttpRequest) {xmlHttp = new XMLHttpRequest ();}}

// Create an XMLHttpRequest object and call the previously defined function creatXMLHTTP (); if (xmlHttp! = Null) {// create a function in response to the status change of the XMLHttpRequest object // create an http request // send an http request} else {alert ("your browser does not support XMLHTTP ");}
2. register the callback function.
// Create the xmlHttp. onreadystatechange = httpStateChange function in response to the status change of the XMLHttpRequest object;
During asynchronous calls, the XMLHttpRequest object has several different states, which indicate the asynchronous call process.
0: The status is not initialized. You just created an XMLHttpRequest object;
1: The initialization status, that is, the XMLHttpRequest object has obtained information such as the server on which the data is to be sent and the method in which the data is sent;
2: sending status. XMLHttpRequest starts to send data;
3: Data Transmission status. At this time, XMLHttpRequest is accepting the data returned from the server, but the data has not been transferred;
4: Completion status: At this time, the XMLHttpRequest object has accepted the data returned from the server.

You can use the onreadystatechange attribute of the XMLHttpRequest object to set a function to respond to the status change of the XMLHttpRequest object.

When setting a callback function, do not add parentheses after the function name. Brackets indicate registering the callback function return value to the onreadystatechange attribute.

3. Use the open method to set basic information for interaction with the server.
// Create an http request xmlHttp. open ("get", "userName.txt", true );
The open (method, URL, flag, name, password) method of XMLHttpRequest is used to initialize an object. The last three parameters are optional. Method: Specifies the method used to send an http request to the server. The parameter values can be get, post, head, put, or delete. URL: Specifies the server URL, that is, the URL of the Program for processing and returning data. This URL can be an absolute or relative address. Flag: Specifies the http request submission method. "true" indicates the asynchronous mode, which is the default value. "false" indicates the synchronous mode. Name and password: if the server needs verification, these two parameters are used to submit the user name and password.

4. Set the sent data to start interacting with the server.

// Send the http request xmlHttp. send (null );

UseSend (data) method of XMLHttpRequestThe data parameter is the parameter of the file specified by the URL parameter passed to the open () method. If multiple parameters are to be passed, they are separated by "&", and "null" is not required ".


5. Check whether the interaction ends and the response is correct in the callback function. Then, obtain the data returned by the server and update the page content as needed.

1) Determine whether the asynchronous call is successful:

If (xmlHttp. readyState = 4) // the asynchronous call is completed {if (xmlHttp. status = 200 | xmlHttp. status = 0) // asynchronous call successful | Debug on the local machine {}}
The value of readyState is 4, indicating that the asynchronous call is completed, but it does not mean that the asynchronous call is successful. The status attribute of XMLHttpRequest can obtain the status code returned from the server. 0 indicates an incomprehensible http status. It is usually returned only when the local computer opens a file. Common http status codes include the following:

200: the server returns the webpage successfully.

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

503: the server response times out.


2) obtain the data returned by the server:

<span style="font-family:SimSun;font-size:18px;"><strong> var userNames = xmlHttp.responseText;</strong></span>

The final purpose of asynchronous calling is to receive the data returned from the server and decide how to display it on the client webpage based on the data. After the asynchronous call is successful, the XMLHttpRequest object obtains the data returned by the server by using the following four attributes.

ResponseText: returns the data returned by the server as a string.

ResponseXML: returned in XML format.

ResponseBody: returned in the form of an unsigned byte array.

ResponseStream: returned as an IStream object.


3) partial update:

<Span style = "font-family: SimSun; font-size: 18px;"> <strong> // find the node var node = document used to display the prompt information. getElementById ("myDiv"); // update the data node. firstChild. nodeValue = text; </strong> </span>

After obtaining the data returned by the server, it will be displayed. Ajax uses DOM to update local data.

InAjaxIn programming, the use of XMLHttpRequest objects is inseparable, and each use is to do these five steps. In the face of repeated things, we have to find a solution. Since this programming step is relatively fixed, it has now been encapsulated, so that code can be reused and programming can be simplified. However, to become a good programmer, it is necessary to take a look at these five steps.






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.