Introduction to attributes and methods of XMLHTTPRequest

Source: Internet
Author: User

1. What is an XMLHTTPRequest object?

The most common definition is: XmlHttp is a set of APIs that can be transmitted over http or receive XML and other data in scripting languages such as Javascript, VbScript, and Jscript. XmlHttp can be used to update part of the webpage without refreshing the entire page. (This function is one of the major features of AJAX :))

Explanation from MSDN: XmlHttp provides the protocol for communication between the client and the http server. The client can send a request to the http server through the XmlHttp object (MSXML2.XMLHTTP. 3.0) and use the Microsoft XML Document Object Model Microsoft? XML Document Object Model (DOM) processes the response.

Here are some external things. In fact, this thing has appeared very early, but in the past, the support of browsers was not enough, and only IE was supported. Therefore, most WEB programmers did not use it, but now the situation has changed a lot. Mozilla and Safari adopt it as the de facto standard, and mainstream browsers are beginning to support XMLHTTPRequest objects. However, it is important to note that XMLHTTPRequest is not yet a W3C standard, so it is slightly different in different browsers.

2. Create an XMLHTTPRequest object

By the way, let's take a look at how to declare (use) it. Before using the XMLHTTPRequest object to send requests and process responses, we must use javascript to create an XMLHTTPRequest object. (IE implements XMLHTTPRequest as an ActiveX object, while other browsers [such as Firefox/Safari/Opear] implement it as a local javascript Object ). Next let's take a look at how to use javascript to create it:

<Script language = "javascript" type = "text/javascript">
<! --
Var xmlhttp;

// Create an XMLHTTPRequest object
Function createXMLHTTPRequest (){
If (window. ActiveXObject) {// determines whether ActiveX controls are supported
Xmlhttp = new ActiveObject ("Microsoft. XMLHTTP"); // create an XMLHTTPRequest object by instantiating a new instance of ActiveXObject
}
Else if (window. XMLHTTPRequest) {// determines whether to implement XMLHTTPRequest as a local javascript Object
Xmlhttp = new XMLHTTPRequest (); // create an instance of XMLHTTPRequest (local javascript Object)
}
}
// -->
</Script>

3. attributes and Methods

Since there are too many things, I will first use a page to list some methods and attributes. I will give you a detailed example later (I am also learning ).

<Html>
<Head>
<Title> DEMO of XMLHTTPRequest object description </title>

<Script language = "javascript" type = "text/javascript">
<! --
Var xmlhttp;

// Create an XMLHTTPRequest object
Function createXMLHTTPRequext ()
{
If (window. ActiveXObject)
{
Xmlhttp = new ActiveXObject ('Microsoft. xmlhttp ');
}
Else if (window. XMLHTTPRequest)
{
Xmlhttp = new XMLHTTPRequest ();
}
}

Function PostOrder (xmldoc)
{
CreateXMLHTTPRequext ();

// Method: open
// Create an http request and specify the method, URL, and authentication information of the request.
// Syntax: oXMLHttpRequest. open (bstrMethod, bstrUrl, varAsync, bstrUser, bstrPassword );
// Parameters
// BstrMethod
// Http method, such as POST, GET, PUT, and PROPFIND. Case Insensitive.

// BstrUrl
// The requested URL, which can be an absolute or relative address.

// VarAsync [Optional]
// Boolean, specifies whether the request is asynchronous. The default value is true. If it is true, the callback function specified by the onreadystatechange attribute is called when the status changes.

// BstrUser [Optional]
// If the server needs to be verified, the user name is specified here. If not, the verification window is displayed when the server needs to be verified.

// BstrPassword [Optional]
// The password section in the verification information. If the user name is empty, this value is ignored.

// Note: after calling this method, you can call the send method to send data to the server.
Xmlhttp. Open ("get", "http: // localhost/example.htm", false );
// Var book = xmlhttp. responseXML. selectSingleNode ("// book [@ id = 'bk101 ']");
// Alert (book. xml );

// Attribute: onreadystatechange
// Onreadystatechange: Specifies the event handling handle when the readyState attribute changes.
// Syntax: oXMLHttpRequest. onreadystatechange = funcMyHandler;
// The following example shows how to call the HandleStateChange function when the readyState attribute of the XMLHTTPRequest object is changed,
// When the data is received (readystate = 4), a button on this page will be activated.
// Note: This attribute is only written, which is an extension of the W3C object model.
Xmlhttp. onreadystatechange = HandleStateChange;

// Method: send
// Send the request to the http server and receive the response
// Syntax: oXMLHttpRequest. send (varBody );
// Parameter: varBody (data to be sent through this request .)
// Note: the synchronous or asynchronous mode of this method depends on the bAsync parameter in the open method. If bAsync = False, this method will not be returned until the request is completed or timed out, if bAsync = True, this method returns immediately.
// This method takes one optional parameter, which is the requestBody to use. the acceptable VARIANT input types are BSTR, SAFEARRAY of UI1 (unsigned bytes), IDispatch to an XML Document Object Model (DOM) object, and IStream *. you can use only chunked encoding (for sending) when sending IStream * input types. the component automatically sets the Content-Length header for all but IStream * input types.
// If the sent data is BSTR, the response is encoded as UTF-8, and a document type header containing charset must be set in the appropriate position.
// If the input type is a SAFEARRAY of UI1, the response is sent as is without additional encoding. The caller must set a Content-Type header with the appropriate content type.
// If the sent data is an xml dom object, the response will be encoded as the encoding declared in the xml document, and if there is no declarative encoding in the xml document, the default UTF-8 will be used.
// If the input type is an IStream *, the response is sent as is without additional encoding. The caller must set a Content-Type header with the appropriate content type.
Xmlhttp. Send (xmldoc );

// Method: getAllResponseHeaders
// Obtain all http headers of the response
// Syntax: strValue = oXMLHttpRequest. getAllResponseHeaders ();
// Note: Each http header name and value are separated by a colon and ended with \ r \ n. This method is called only after the send method is complete.
Alert (xmlhttp. getAllResponseHeaders ());

// Method: getResponseHeader
// Obtain the specified http header from the response information
// Syntax: strValue = oXMLHttpRequest. getResponseHeader (bstrHeader );
// Note: This method can be called only when the send method is successful. If the document type returned by the server is "text/xml ",
// Xmlhttp. getResponseHeader ("Content-Type"); returns the string "text/xml ". You can use the getAllResponseHeaders method to obtain the complete http header information.
Alert (xmlhttp. getResponseHeader ("Content-Type "));
// Output the Content-Type column in the http header: version and name of the current web server.

Document. frmTest. myButton. disabled = true;
// Method: abort
// Cancel the current request
// Syntax: oXMLHttpRequest. abort ();
// Note: after this method is called, the current request returns the UNINITIALIZED status.
// Xmlhttp. abort ();

// Method: setRequestHeader
// Specify an http header of the Request separately
// Syntax: oXMLHttpRequest. setRequestHeader (bstrHeader, bstrValue );
// Parameter: bstrHeader (string, header name .)
//? BstrValue (string, value .)
// Note: if an http header with the name already exists, overwrite it. This method must be called after the open method.
// Xmlhttp. setRequestHeader (bstrHeader, bstrValue );

}

Function HandleStateChange ()
{
// Attribute: readyState
// Return the current status of the XMLHTTP request
// Syntax: lValue = oXMLHttpRequest. readyState;
// Remarks: variable. This attribute is read-only and the status is expressed in an integer of 4. The definition is as follows:
// 0 (not initialized) the object has been created, but has not been initialized (the open method has not been called)
// 1 (initialization) the object has been created and the send method has not been called
// 2 (send data) The send method has been called, but the current status and http header are unknown
// 3 (data transmission in progress) Some data has been received. Because the response and http headers are incomplete, an error occurs when retrieving part of data through responseBody and responseText,
// 4 (complete) After receiving the data, you can use responseBody and responseText to obtain the complete response data.
If (xmlhttp. readyState = 4)
{
Document. frmTest. myButton. disabled = false;

// Property: responseBody
// Return the server response data in a certain format
// Syntax: strValue = oXMLHttpRequest. responseBody;
// Remarks: variable. This attribute is read-only and represents undecoded binary data directly returned from the server in unsigned array format.
Alert (xmlhttp. responseBody );

// Attribute: responseStream
// Return the response information in the form of an Ado Stream Object
// Syntax: strValue = oXMLHttpRequest. responseStream;
// Remarks: variable. This attribute is read-only and returns the response information in the form of an Ado Stream object.
Alert (xmlhttp. responseStream );

// Property: responseText
// Return response information as a string
// Syntax: strValue = oXMLHttpRequest. responseText;
// Remarks: variable. This attribute is read-only and the response is returned as a string. XMLHTTP tries to decode the response to a Unicode string,
// XMLHTTP encodes the response data as a UTF-8 by default. If the data returned by the server includes BOM (byte-order mark), XMLHTTP can
// To decode any UCS-2 (big or little endian) or UCS-4 data. Note: If the server returns an xml document, this is
// Does not process the encoding declaration in the xml document. You need to use responseXML for processing .?
Alert (xmlhttp. responseText );

// Property: responseXML
// Format the response information as an Xml Document Object and return
// Syntax: var objDispatch = oXMLHttpRequest. responseXML;
// Remarks: variable. This attribute is read-only and the response information is formatted as an Xml Document Object and returned. If the response data is not a valid XML document,
// This attribute does not return XMLDOMParseError. You can obtain error information through the DOMDocument object that has been processed.
Alert ("Result =" + xmlhttp. responseXML. xml );

// Attribute: status
// Return the http status code of the current request
// Syntax: lValue = oXMLHttpRequest. status;
// Return value: standard http status code for long shaping, which is defined as follows:
// Number: Description?
// 100: Continue
/// 101: Switching protocols
/// 200: OK
/// 201: Created
/// 202: Accepted
// 203: Non-Authoritative Information
// 204: No Content
/// 205: Reset Content
// 206: Partial Content
/// 300: Multiple Choices
// 301: Moved Permanently
/// 302: Found
// 303: See Other
// 304: Not Modified
/// 305: Use Proxy
// 307: Temporary Redirect
/// 400: Bad Request
/// 401: Unauthorized
// 402: Payment Required
/// 403: Forbidden
// 404: Not Found
// 405: Method Not Allowed
/// 406: Not Acceptable
// 407: Proxy Authentication Required
// 408: Request Timeout
/// 409: Conflict
/// 410: Gone
/// 411: Length Required
/// 412: Precondition Failed
// 413: Request Entity Too Large
/// 414: Request-URI Too Long
// 415: Unsupported Media Type
// 416: Requested Range Not Suitable
/// 417: Expectation Failed
// 500: Internal Server Error
// 501: Not Implemented
/// 502: Bad Gateway
// 503: Service Unavailable
// 504: Gateway Timeout
// 505: HTTP Version Not Supported
// Remarks: long integer. This attribute is read-only and returns the http status code of the current request. This attribute can be obtained only after data is sent and received.
Alert (xmlhttp. status );

// Attribute: statusText
// Return the response line status of the current request
// Syntax: strValue = oXMLHttpRequest. statusText;
// Remarks: String. This attribute is read-only and returns the response row status of the current request with BSTR. This attribute can be obtained only after data is sent and received.
Alert (xmlhttp. statusText );
}
}

// -->
</Script>

</Head>
<Body>
<Form name = "frmTest">
<Input name = "myButton" type = "button" value = "Click Me" onclick = "PostOrder ('HTTP: // localhost/example.htm');">
</Form>
</Body>
</Html>

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.