Ajax and XMLHttpRequest objects

Source: Internet
Author: User
XMLHttpRequest is the object of the XMLHTTP component. With this object, AJAX can be used as a desktop application. Program In the same way, only the data layer is exchanged with the server, without refreshing the interface every time, or having to submit the data processing work to the server every time; in this way, the server load is reduced, the response speed is recalled, and the user's waiting time is shortened.
XMLHTTPRequest object and Ajax
In Ajax applications, the XMLHTTPRequest object sends user information to the server asynchronously and receives server response information and data.
It should be noted that JavaScript itself does not have the ability to send requests to the server, or use window. the open () method re-opens a page, or uses the XMLHTTPRequest object to send requests. The difference is that the former is normal, that is, synchronous interaction mode, and the latter is Asynchronous interaction mode.
Attributes and methods of the XMLHTTPRequest object.
Starting from ie5.0, developers can use the XMLHTTP ActiveX component to expand their functions on the web page, while illa1.0 and netscape7 are used to create XML-inherited XMLHttpRequest proxies; in most cases, XMLHttpRequest and XMLHTTP components are similar. Methods and attributes are similar, but some attributes are different. Below Code Demonstrate how to create an XMLHTTPRequest object in IE, Netscape, and other browsers.

< Script Language = "JavaScript" >
// Define a variable
VaR Http_request =   False ;
// Create in IE
Http_request =   New Activexobject ( " Msxml2.xmlhttp " ); // New version IE
Http_request =   New Activexobject ( " Microsoft. XMLHTTP " ); // Old version IE
// Netscope Browser
Http_request =   New XMLHttpRequest ();
</ Script >

It should be noted that XMLHttpRequest is also supported in Microsoft's latest ie7.0 browser, that is, both the above two creation methods are supported in ie7.0. When developing Ajax applications, be sure to be compatible with the browser type.
The creation method can be as follows:

VaR Http_request =   False ;
Function Createxmlhttprequest ()
{
Http_request =   False ;
// Start initializing the XMLHTTPRequest object
If (Window. XMLHttpRequest) // If it is a window. XMLHTTPRequest object
{
// Mozilla and Netscape browsers
Http_request =   New XMLHttpRequest ();
If (Http_request.overridemimetype) {//Set mime category
//Some browsers report an error when processing the content returned by the server that does not contain the XML mime-type header. Therefore, ensure that the returned content contains text/XML Information.
Http_request.overridemimetype ("Text/XML");
}
}
Else   If (Window. activexobject) // For window. activexobject
{
// IE browser
Try
{
Http_request= NewActivexobject ("Msxml2.xmlhttp");//Newer version of IE
}
Catch (E)
{
Try
{
Http_request= NewActivexobiect ("Microsoft. XMLHTTP");//Earlier version of IE
}
Catch (E) {}
}
}
If ( ! Http_request)
{
//An exception occurred while creating the object instance.
Window. Alert ("You cannot create an XMLHTTPRequest object instance.");
Return False;
}
}

This is a simple cross-browser creation method.

In addition, the XMLHTTPRequest object provides a series of attributes and methods to initiate asynchronous HTTP requests to the server, listen to the server status, and receive the information data returned by the server after the server completes data Response Processing. The following is a description of it:
XMLHTTPRequest object attributes

Onreadystatechange : Specifies the event processing handle when the readystate attribute changes. The attribute is only written.
The XMLHTTPRequest object attribute onreadystatechange is an event trigger for readystate state change. It is used to specify the processing event when the readystate attribute changes. When using the event processing function, you can assign the event processing function name to onreadystatechange to specify the event trigger for XMLHttpRequest. In the event processing function, you can determine the readystate value and perform corresponding processing.
As shown above: http_request.onreadystatechange = processrequest; processrequest is used as the event processing function and is executed when the readystate status in the processrequest function is 4.
Readystate : Returns the status of the current request. The attribute is read-only.
These statuses are represented by integer data with a length of 4. The status of these statuses is described as follows:
0: not initialized (the object has been created but not initialized, that is, the open method has not been called to create an HTTP request)
1: initialization (the object has been created, but the send method has not been called to send an HTTP request)
2: send data (the send method has been called, but the current status and HTTP header are unknown)
3: data transmission is in progress (some data has been received because the response and HTTP headers are incomplete. In this case, an error occurs when obtaining part of data through the response system method)
4: The transfer is complete. (after the data is complete, you can use the response system method to obtain the complete response data)
Responsebody : The Response Message Body is returned in the form of an unsigned byte array, and the attribute is read-only.
Responsetext : Return the server response information in the form of a string. The attribute is read-only.
Responsexml : Format the response information as an XML Document Object and return it. The attribute is read-only.

The XMLHTTPRequest object Method and Its Meaning are as follows: :
Abort : Cancels the current request;
Syntax: http_request.abort (); call this method. The uninitialized status is returned for the current request.
Getallresourceheaders : Get all the corresponding HTTP header information. Like the httpservletrequest object in JSP, get the HTTP request header information. Syntax: headers = http_request.getallresourceheaders ();
Getresourceheader : Obtain the specified HTTP header from the response information.
Syntax: Head = http_request.getresourceheader ("header-name ");
Open : Create an HTTP request and specify the method, URL, and authentication information (User Name/password) of the request ).
Syntax: http_request.open (method, URL, async, user, password );
Async is a Boolean value that specifies whether the request is asynchronous. The default value is true. If it is true, it is called when the state changes. Onreadystatechange The callback function to which the property points. If the server requires authentication, specify the user name and password.
Send : Send a request to the HTTP server and receive a response. After creating an HTTP request, you can send an HTTP request to the server. The send method is called.
Syntax: http_request.send (varbody );
The varbody parameter is the content to be sent to the server. If there is no content to send, the varbody parameter can be omitted, but it is better to write it as null, because if it is omitted and not written in firfox, an error is returned, so it is http_request.send (null );. The synchronous or Asynchronous Method of this method depends on the async parameter in the open method.
SetRequestHeader : Separately set a request header.
Status : Return the status code of the current HTTP request. The attribute is read-only. For example: 404 = "file not found", 200 = "successful"
Statustext : Return the status line of the current HTTP request. The attribute is read-only.

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.