An important technology (tool) used when designing AJAX is the XMLHTTPRequest object. The XMLHttpRequest object is the technical foundation for all AJAX and Web 2.0 applications today. Although software vendors and open source communities are now providing various AJAX frameworks to further simplify the use of the XMLHttpRequest object; however, it is still necessary for us to understand the properties and methods of this object.
1. What is the XMLHTTPRequest object?
The most common definition is: XmlHttp is a set of APIs that can transmit or receive XML and other data through the http protocol in JavaScript, VbScript, Jscript and other scripting languages. The biggest use of XmlHttp is that it can update part of the content of a web page without refreshing the entire page. (This function is one of the major features of AJAX)
Explanation from MSDN: XmlHttp provides a protocol for the client to communicate with 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) to process the response.
Let me digress here. In fact, this thing has appeared very early. However, the browser support was not enough in the past. It was only supported in IE, so most WEB programmers did not use it very much. But now the situation has changed a lot. , Mozilla and Safari adopted it as a de facto standard, and mainstream browsers began to support the XMLHTTPRequest object. But what needs to be emphasized here is that XMLHTTPRequest is not yet a W3C standard, so the performance on different browsers is slightly different.
2. Create an XMLHTTPRequest object
Speaking of differences, 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, and other browsers [such as Firefox/Safari/Opear] implement it as a native javascript object). Let's take a look at how to use JavaScript to create it:
The following is a quote:
<script language="javascript" type="text/javascript">
<!--
var xmlhttp;
//Create XMLHTTPRequest object
function createXMLHTTPRequest(){
if(window.ActiveXObject){ // Determine whether ActiveX control is supported
xmlhttp = new ActiveObject("Microsoft.XMLHTTP"); // Create an XMLHTTPRequest object by instantiating a new instance of ActiveXObject
}
else if(window.XMLHTTPRequest){ // Determine 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 use this page to list the methods and attributes. I will give detailed examples later (mainly because I am also learning).
<html>
<head>
<title>Description of XMLHTTPRequest object DEMO</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 a new http request and specify the request method, URL and verification information
// Syntax: oXMLHttpRequest.open(bstrMethod, bstrUrl, varAsync, bstrUser, bstrPassword);
//parameters
// bstrMethod
//http methods, such as: POST, GET, PUT and PROPFIND. Case insensitivity.
// bstrUrl
//The requested URL address can be an absolute address or a relative address.
// varAsync[optional]
// Boolean type, specifies whether this request is asynchronous. The default is true. If true, the callback function specified by the onreadystatechange attribute will be called when the state changes.
// bstrUser[optional]
// If the server requires verification, specify the username here. If not specified, a verification window will pop up when the server requires verification.
// bstrPassword[optional]
// The password part of the verification information. If the username is empty, this value will be 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: Specify the event handler when the readyState property changes
// Syntax: oXMLHttpRequest.onreadystatechange = funcMyHandler;
// The following example demonstrates calling the HandleStateChange function when the readyState property of the XMLHTTPRequest object changes.
// When the data is received (readystate == 4) a button on this page will be activated
// Note: This property is write-only and is an extension of the W3C Document Object Model.
xmlhttp.onreadystatechange= HandleStateChange;
// Method: send
//Send request to http server and receive response
// Syntax: oXMLHttpRequest.send(varBody);
// Parameters: 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 wait for the request to complete or timeout before returning. If bAsync == True, this method will immediately return. return.
// 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 data sent 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 data sent is an XML DOM object, the response will be encoded to the encoding declared in the xml document. If no encoding is declared 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
// Get all http headers of the response
// Syntax: strValue = oXMLHttpRequest.getAllResponseHeaders();
// Note: Each http header name and value are separated by colon and end with rn. This method can be called only after the send method is completed.
alert(xmlhttp.getAllResponseHeaders());
// Method: getResponseHeader
// Get the specified http header from the response information
// Syntax: strValue = oXMLHttpRequest.getResponseHeader(bstrHeader);
// Note: This method can be called only after the send method succeeds. If the document type returned by the server is "text/xml", then this sentence
// xmlhttp.getResponseHeader("Content-Type"); will return the string "text/xml". You can use the getAllResponseHeaders method to obtain complete http header information.
alert(xmlhttp.getResponseHeader("Content-Type")); // Output the Content-Type column in the http header: the version and name of the current web server.
document.frmTest.myButton.disabled = true;
// Method: abort
//Cancel current request
// Syntax: oXMLHttpRequest.abort();
// Note: After calling this method, the current request returns UNINITIALIZED status.
//xmlhttp.abort();
// Method: setRequestHeader
// Separately specify a certain http header of the request
// Syntax: oXMLHttpRequest.setRequestHeader(bstrHeader, bstrValue);
// Parameters: bstrHeader (String, header name.)
// bstrValue(String, value.)
// Note: If an http header with this name already exists, it will be overwritten. 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 represented by an integer of length 4. The definition is as follows:
// 0 (uninitialized) The object has been created, but has not been initialized (the open method has not been called yet)
// 1 (initialization) The object has been created and the send method has not been called yet.
// 2 (Send data) The send method has been called, but the current status and http header are unknown
// 3 (Data is being transmitted) Part of the data has been received. Because the response and http headers are incomplete, an error will occur when obtaining part of the data through responseBody and responseText.
// 4 (Complete) Data reception is completed. At this time, the complete response data can be obtained through responseBody and responseText.
if (xmlhttp.readyState == 4){
document.frmTest.myButton.disabled = false;
// Attribute: responseBody
// Return server response data in a certain format
// Syntax: strValue = oXMLHttpRequest.responseBody;
// Remarks: Variable, this property is read-only and represents the undecoded binary data returned directly from the server in unsigned array format.
alert(xmlhttp.responseBody);
//Property: responseStream
//Return response information in the form of Ado Stream object
// Syntax: strValue = oXMLHttpRequest.responseStream;
// Remarks: Variable, this property is read-only and returns response information in the form of an Ado Stream object.
alert(xmlhttp.responseStream);
//Attribute: responseText
// Return the response information as a string
// Syntax: strValue = oXMLHttpRequest.responseText;
// Remarks: Variable, this property is read-only and returns the response information as a string. XMLHTTP attempts to decode the response information into a Unicode string,
// XMLHTTP sets the encoding of response data to UTF-8 by default. If the data returned by the server contains BOM (byte-order mark), XMLHTTP can
// To decode any UCS-2 (big or little endian) or UCS-4 data. Note that if the server returns an xml document, this attribute
// Properties do not handle encoding declarations in xml documents. You need to use responseXML to handle it.
alert(xmlhttp.responseText);
//Attribute: responseXML
//Format the response information into an Xml Document object and return it
// Syntax: var objDispatch = oXMLHttpRequest.responseXML;
// Remarks: Variable, this property is read-only, format the response information into an Xml Document object and return it. If the response data is not a valid XML document,
// This property itself does not return XMLDOMParseError, and error information can be obtained through the processed DOMDocument object.
alert("Result = " + xmlhttp.responseXML.xml);
//Attribute: status
// Return the http status code of the current request
// Syntax: lValue = oXMLHttpRequest.status;
// Return value: long standard http status code, 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
// Note: long integer, this property is read-only and returns the http status code of the current request. This property can only be obtained after the data is sent and received.
alert(xmlhttp.status);
//Attribute: statusText
// Return the response row status of the current request
// Syntax: strValue = oXMLHttpRequest.statusText;
// Remarks: String, this property is read-only. It returns the response row status of the current request in BSTR. This property can only be obtained after the 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>