XMLHTTPRequest object description

Source: Internet
Author: User

Note: This document is from www.w3school.com.cn and is only used for personal learning.

<1>. XMLHttpRequest description:

The XMLHTTPRequest object provides full access to the HTTP protocol, including the ability to make post and head requests and common GET requests. XMLHttpRequest can return the response of the Web server synchronously or asynchronously, and can return content in the form of text or a DOM document.

Although the name is XMLHttpRequest, it is not limited to use with XML documents: it can receive any form of text documents. The XMLHTTPRequest object is a key feature of the Ajax web application architecture.

Function, which can:
Update the webpage without reloading the page
Request data from the server after the page has been loaded
Receive data from the server after the page is loaded
Send data to the server in the background
All modern browsers support XMLHttpRequest objects.

<2>. Create an XMLHTTPRequest object

You can create an XMLHTTPRequest object with a simple line of JavaScript code.

All modern browsers (IE7) use:
XMLHTTP = new XMLHttpRequest ()
Use in ie5 and IE6:
XMLHTTP = new activexobject ("Micrsoft. XMLHTTP ")

<3>. attributes:

1. readystate
HTTP Request status. When an XMLHttpRequest is created for the first time, the value of this attribute starts from 0 until the complete HTTP response is received. This value is increased to 4.

Status Name Description
0 uninitialized initialization status. The XMLHTTPRequest object has been created or reset by the abort () method.
1. The open () method has been called, but the send () method has not. The request has not been sent.
2. The sent send () method has been called, and the HTTP request has been sent to the web server. No response is received.
3. All the Response Headers of the processing ing have received the request. The response body starts receiving but is not completed.
4. The loaded HTTP response has been fully received.
Note: The value of readystate will not decrease unless the abort () or open () method is called during the processing of a request. The onreadystatechange event handle is triggered every time the value of this attribute is increased.

2. responsetext
The response body received by the server (excluding the header) So far, or if no data is received, it is a null string.
If readystate is less than 3, this attribute is an empty string. When readystate is 3, this attribute returns the response that has been received. If readystate is 4, this attribute stores the complete response body.
If the response contains a header that specifies the character encoding for the response body, this encoding is used. Otherwise, it is assumed that the Unicode UTF-8 is used.

3. responsexml

The response to the request is parsed as XML and usedDocument Object.

4. Status

Returned by the serverHTTP status code, For example, 200 indicates successful, and 404 indicates "not found" error. When readystate is less than 3, reading this attribute will cause an exception.

5. statustext

This attribute specifies the HTTP status code of the request by name rather than number. That is to say, when the status is 200, it is "OK", and when the status is 404, it is "not found ". Like the status attribute, when readystate is less than 3, reading this attribute causes an exception.

<4> event handle

1. onreadystatechange

The event handle function called every time the readystate attribute is changed. When readystate is 3, it may also be called multiple times.

<5> Method

1. Abort ()

This method resets the XMLHTTPRequest object to the readystate to 0 and cancels all pending network activities. For example, if the request takes too long and the response is no longer necessary, you can call this method.

2. getAllResponseHeaders ()

Return the HTTP Response Header as an unparsed string.

If readystate is less than 3, this method returns NULL. Otherwise, it returns the headers of all HTTP responses sent by the server. The header is returned as a single string, with one header in one row. Each line is separated by the linefeed "/R/N.

3. getResponseHeader ()

Returns the specified HTTPResponse Header Value. The parameter is the name of the HTTP response header to be returned. You can use any case to specify the header name, which is case insensitive to the response header.

4. open ()

Initialize HTTP request parameters, such as URLs and HTTP methods, but do not send requests.

5. Send ()

Send an HTTP request, use the parameters passed to the open () method, and the optional request body passed to the method.

6. setRequestHeader ()

Set or add an HTTP request to an opened but not sent request.

7. XMLHttpRequest. open ()

Initialize HTTP Request Parameters

Syntax: open (method, URL, async, username, password)

The method parameter is the HTTP Method Used for the request. Values include get, post, and head.
The URL parameter is the request body. Most browsers implement a same-source security policy and require that the URL have the same host name and port as the text containing the script.
The async parameter indicates that the request should be executed asynchronously. If this parameter is set to false, the request is synchronized, and subsequent calls to send () will be blocked until the response is fully received. If this parameter is true or omitted, the request is asynchronous and usually requires an onreadystatechange event handle.
The username and password parameters are optional and provide authentication qualifications for URL Authorization. If they are specified, they will overwrite any qualifications specified by the URL itself.

Note: This method initializes Request Parameters for later use by the send () method. It sets readystate to 1, deletes all previously specified request headers and all previously received response headers, and sets the responsetext, responsexml, status, and statustext parameters as their default values.

8. XMLHttpRequest. Send ()

Send an HTTP request

Syntax: Send (Body)

If the HTTP method specified by calling open () is post or put, the body parameter specifies the Request body as a string or document object. If the request body is not required, this parameter is null. This parameter is unavailable for any other method and should be null (some implementations cannot omit this parameter ).

Note: This method causes an HTTP request to be sent. If open () is not called before, or, more specifically, if readystate is not 1, send () throws an exception. Otherwise, it sends an HTTP request consisting of the following parts: a) the HTTP method, URL, and authentication qualification (if any) specified when open () is called ). B) The request header specified when setRequestHeader () was called (if any ).
C) The body parameter passed to this method.
Once the request is sent, send () sets readystate to 2 and triggers the onreadystatechange event handle.

9. XMLHttpRequest. setRequestHeader ()

Syntax: setRequestHeader (name, value)
The name parameter is the name of the header to be set. This parameter should not contain white spaces, colons, or line breaks.
The value parameter is the value of the header. This parameter should not contain line breaks.

Note: the setRequestHeader () method specifies the header of an HTTP request, which should be included in the request published through a subsequent send () call. This method can be called only when readystate is 1. For example, after open () is called, but before send () is called.

<6> instance

<SCRIPT type = "text/JavaScript">
VaR XMLHTTP;
Function loadxmldoc (URL)
{
XMLHTTP = NULL;
If (window. XMLHttpRequest)
{// Code for all new browsers
XMLHTTP = new XMLHttpRequest ();
}
Else if (window. activexobject)
{// Code for ie5 and IE6
XMLHTTP = new activexobject ("Microsoft. XMLHTTP ");
}
If (XMLHTTP! = NULL)
{
XMLHTTP. onreadystatechange = state_change;
XMLHTTP. Open ("get", URL, true); // true indicates that the script will continue to be executed after the send () method, without waiting for the response from the server
XMLHTTP. Send (null );
}
Else
{
Alert ("your browser does not support XMLHTTP .");
}
}

Function state_change ()
{
If (XMLHTTP. readystate = 4)
{// 4 = "loaded"
If (XMLHTTP. Status = 200)
{// 200 = OK
//... Our code here...
}
Else
{
Alert ("problem retrieving XML data ");
}
}
}
</SCRIPT>

Note: onreadystatechange is an event handle. Its value (state_change) is the name of a function. This function is triggered when the status of the XMLHTTPRequest object changes. The status changes from 0 (uninitialized) to 4 (complete. The code is executed only when the status is 4.

Replace //... our code here with: Document. getelementbyid ('t1'). innerhtml = XMLHTTP. responsetext;
You can use XMLHTTP to load a textfile into an element whose ID is 't1 '.
Change to: Document. getelementbyid ('p1'). innerhtml = XMLHTTP. getAllResponseHeaders ();
You can implement the head request function through XMLHTTP.
Change to: Document. getelementbyid ('p1'). innerhtml = XMLHTTP. getResponseHeader ('Last-modified ');
You can implement the specified head request through XMLHTTP.
Change to: xforwarxmlhttp.responsexml.doc umentelement. getelementsbytagname ("cd ");
Then use: xx = x [I]. getelementsbytagname ("title ");
TXT = XX [0]. firstchild. nodevalue;
You can get all element values in the corresponding XML file.

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.