[Convert] ajax_xmlhttprequest object details
XMLHTTPRequest object is the technical basis of all Ajax and Web 2.0 applications today. Although software dealers and open-source communities are currently providing various Ajax frameworks to further simplify the use of XMLHttpRequest objects, we still need to understand the detailed working mechanism of this object.
I. Introduction
Asynchronous JavaScript and XML (Ajax) are special terms used to implement data interaction between client scripts and servers. The advantage of this technology is that it provides developers with a way to retrieve data from the Web server without returning the pages that users are currently observing to the server. Programming with modern browsers by accessing the browser Dom StructureCode(JavaScript) dynamically adjusts the support for the displayed content. Ajax allows developers to update the displayed HTML content on the browser without refreshing the page. In other words, Ajax enables browser-based applicationsProgramMore interactive and similar to traditional desktop applications.
Google's Gmail and Outlook Express are two familiar examples of Ajax technology. Besides, AJAX can be used in any client scripting language, including JavaScript, JScript, and VBScript.
Ajax uses XMLHttpRequest, an object built into all modern browsers, to send and receive HTTP requests and responses. An HTTP request sent through an XMLHTTPRequest object does not require the page to have or send back a <form> element. "A" in Ajax represents "Asynchronous", which means that the send () method of the XMLHTTPRequest object can be returned immediately, in this way, other html/JavaScript on the web page can be processed by the browser, and the server processes HTTP requests and sends responses. Although the request is asynchronous by default, you can choose to send a synchronous request, which will suspend the processing of other web pages until the page receives a response from the server.
Microsoft introduced the XMLHTTPRequest object as an ActiveX Object in Internet Explorer (IE) 5. Other browser manufacturers that recognize the importance of this object have also implemented XMLHttpRequest objects in their browsers, but as a local JavaScript Object rather than an ActiveX object. Now, after realizing the value and security features of this type, Microsoft has implemented XMLHttpRequest as a window object attribute in its IE 7. Fortunately, although its implementation (and thus the call method) is different, all browser implementations have similar functions and are essentially the same method. Currently, W3C organizations are working to standardize XMLHttpRequest objects and have released a draft on this W3C specification.
This article will discuss in detail the XMLHTTPRequest object API and explain all its attributes and methods.
Ii. attributes and events of the XMLHTTPRequest object
The XMLHTTPRequest object exposes various attributes, methods, and events to facilitate scripting and control HTTP requests and responses. Next, we will discuss this in detail.
Readystate attributes
When an XMLHTTPRequest object sends an HTTP request to the server, it goes through several states: waiting until the request is processed; then, it receives a response. In this way, the script correctly responds to various statuses-the XMLHTTPRequest object exposes the readystate attribute describing the current state of the object, as shown in table 1.
Readystate attributes
Table 1. List of readystate attribute values of the XMLHTTPRequest object.
Readystate Value |
Description |
0 |
Describes the state of "not initialized". At this time, an XMLHTTPRequest object has been created but has not been initialized. |
1 |
Describes a "send" status. At this time, the Code has called the XMLHttpRequest open () method and XMLHttpRequest is ready to send a request to the server. |
2 |
Describes a "send" status. At this time, a request has been sent to the server through the send () method, but no response has been received. |
3 |
Description: A "receiving" status. At this time, the HTTP response header information has been received, but the message body has not completely received. |
4 |
Describes a "loaded" status. At this time, the response has been fully received. |
Onreadystatechange event
No matter when the value of readystate changes, the XMLHTTPRequest object will trigger a readystatechange event. The onreadystatechange property receives an eventlistener value-instructs the method that the object will be activated no matter when the value of readystate changes.
Responsetext attributes
This responsetext property contains the text content of the HTTP response received by the client. When the value of readystate is 0, 1, or 2, responsetext contains an empty string. When the value of readystate is 3 (receiving), the response contains the uncompleted response information from the client. When readystate is 4 (loaded), The responsetext contains the complete response information.
Responsexml attributes
This responsexml attribute is used to describe the XML response when a complete HTTP response is received (readystate is 4). In this case, the Content-Type Header specifies that the mime (media) type is text/XML, application/XML may end with + XML. If the Content-Type Header does not contain any of these media types, the responsexml value is null. Whenever the value of readystate is not 4, the value of responsexml is also null.
In fact, this responsexml property value is a document interface type object used to describe the document to be analyzed. If the document cannot be analyzed (for example, if the document is not a good structure or does not support the corresponding character encoding of the document), the value of responsexml is null.
Status attribute
This status attribute describes the HTTP status code and its type is short. This status attribute is available only when the readystate value is 3 (receiving) or 4 (loaded. When the value of readystate is less than 3, an exception is thrown when you try to access the value of status.
Statustext attributes
This statustext attribute describes the HTTP status code text, and is available only when the readystate value is 3 or 4. When readystate is another value, an exception occurs when you attempt to access the statustext attribute.
3. XMLHTTPRequest object Method
The XMLHTTPRequest object provides various methods for initializing and processing HTTP requests.
Abort () method
You can use this abort () method to pause the HTTP request associated with an XMLHTTPRequest object and reset the object to the uninitialized state.
Open () method
You need to call the open (domstring method, domstring Uri, Boolean async, domstring username, domstring password) method to initialize an XMLHTTPRequest object. The method parameter must be provided to specify the HTTP method (get, post, put, delete, or head) You want to send the request ). To send data to the server, the POST method should be used; to retrieve data from the server, the get method should be used. In addition, the URI parameter is used to specify the URI of the server to which the XMLHTTPRequest object sends the request. The URI is parsed as an absolute URI-in other words, you can use a relative URI-it will be parsed in the same way as the URI relative to browser resolution. The async parameter specifies whether the request is asynchronous-the default value is true. To send a synchronous request, you must set this parameter to false. For servers that require authentication, You can provide optional user name and password parameters. After the open () method is called, the XMLHTTPRequest object sets its readystate attribute to 1 (open) and resets the responsetext, responsexml, status, and statustext attributes to their initial values. In addition, it resets the request header. Note: If you call the open () method and the readystate is 4 at this time, the XMLHTTPRequest object will reset these values.
Send () method
After a request is prepared by calling the open () method, you need to send the request to the server. You can call the send () method only when the value of readystate is 1. Otherwise, the XMLHTTPRequest object will cause an exception. The request is sent to the server using parameters provided to the open () method. When the async parameter is true, the send () method returns immediately, allowing other client scripts to continue processing. After the send () method is called, the XMLHTTPRequest object sets the value of readystate to 2 (send ). When the server responds, if any message body exists before receiving the message body, the XMLHTTPRequest object sets readystate to 3 (receiving ). When the request completes loading, it sets readystate to 4 (loaded ). For a head-type request, it will set it to 4 immediately after setting the readystate value to 3.
The send () method uses an optional parameter-this parameter can contain variable types of data. Typically, you use it and send data to the server through the POST method. In addition, you can explicitly call the send () method using the null parameter, which is the same as calling it without a parameter. For most other data types, use the setRequestHeader () method (see the description below) to set the Content-Type Header before calling the send () method. If the type of the Data parameter in the send (data) method is domstring, the data is encoded as the UTF-8. If the data type is document, the data will be serialized using the encoding specified by data. xmlencoding.
SetRequestHeader () method
The setRequestHeader (domstring header, domstring value) method is used to set the request header information. When the value of readystate is 1, you can call this method after calling the open () method; otherwise, you will get an exception.
GetResponseHeader () method
The getResponseHeader (domstring header, value) method is used to retrieve the response header value. This method can be called only when the value of readystate is 3 or 4 (in other words, after the response header is available); otherwise, an empty string is returned.
GetAllResponseHeaders () method
The getAllResponseHeaders () method returns all Response Headers in the form of a string (each header occupies a single line ). If the value of readystate is not 3 or 4, this method returns NULL.
4. Send a request
In Ajax, many requests that use XMLHttpRequest are initiated from an HTML event (for example, an onclick button that calls a JavaScript function or an onkeypress. Ajax supports various applications, including form verification. Sometimes, a unique form field is required to be verified before filling in other content of the form. For example, you must use a unique userid for the registration form. If Ajax technology is not used to verify this USERID field, the entire form must be filled and submitted. If this userid is not valid, the form must be resubmitted. For example, a form field corresponding to a catalog ID that requires verification on the server may be specified in the following form:
<Form name = "validationform" Action = "validateform" method = "Post"> <Table> <Tr> <TD> catalog ID: </TD> <TD> <Input type = "text" size = "20" id = "catalogid" name = "catalogid" AutoComplete = "off" onkeyup = "sendrequest ()"> </TD> <TD> <Div id = "validationmessage"> </div> </TD> </Tr> </Table> </form> |
The preceding HTML uses validationmessage Div to display a verification message corresponding to the input domain catalog ID. The onkeyup event calls a javascript sendrequest () function. This sendrequest () function creates an XMLHTTPRequest object. The process of creating an XMLHTTPRequest object varies with browser implementations. If the browser supports the XMLHTTPRequest object as a window attribute (this applies to all common browsers except ie 5 and IE 6), the code can call the XMLHttpRequest constructor. If the browser implements the XMLHTTPRequest object as an activexobject object (like in IE 5 and IE 6), the code can use the activexobject constructor. The following function calls an Init () function, which is responsible for checking and deciding the appropriate creation method to use-before creating and returning objects.
<SCRIPT type = "text/JavaScript"> Function sendrequest (){ VaR xmlhttpreq = Init (); Function Init (){ If (window. XMLHttpRequest ){ Return new XMLHttpRequest (); } Else if (window. activexobject ){ Return new activexobject ("Microsoft. XMLHTTP "); } } </SCRIPT> |
Next, you need to use the open () method to initialize the XMLHTTPRequest object-specify the HTTP method and the server URL to be used.
VaR catalogid = encodeuricomponent (document. getelementbyid ("catalogid"). value ); Xmlhttpreq. Open ("get", "validateform? Catalogid = "+ catalogid, true ); |
By default, HTTP requests sent using XMLHttpRequest are asynchronous, but you can explicitly set the async parameter to true, as shown above.
In this case, the URL validateform call will activate a servlet on the server, but you should be able to note that the server-side technology is not fundamental; in fact, the URL may be an ASP, Asp. net or PHP page or a Web Service-this does not matter as long as the page returns a response-indicating whether the catalogid value is valid. Because you are making an asynchronous call, you need to register an XMLHTTPRequest object to call the callback event processor-called when its readystate value changes. Remember, changing the value of readystate will trigger a readystatechange event. You can use the onreadystatechange attribute to register the callback event processor.
Xmlhttpreq. onreadystatechange = processrequest; |
Then, we need to use the send () method to send the request. Because this request uses the http get method, you can call the send () method without specifying a parameter or using a null parameter.
Xmlhttpreq. Send (null ); |
5. Process requests
In this example, because the HTTP method is get, the receiving servlet on the server will call a doget () method, which will retrieve the value of the catalogid parameter specified in the URL, and check its validity from a database.
In this example, the servlet needs to construct a response sent to the client. In addition, the XML type is returned in this example. Therefore, it sets the HTTP content type of the response to text/XML and the cache-control header to no-cache. Setting the cache-control header prevents the browser from simply reloading pages from caching.
Public void doget (httpservletrequest request, Httpservletresponse response) Throws servletexception, ioexception { ... ... Response. setcontenttype ("text/XML "); Response. setheader ("cache-control", "No-Cache "); } |
The response from the server is an xml dom object that creates an XML string containing instructions to be processed on the client. In addition, the XML string must have a root element.
Out. println ("<catalogid> valid </catalogid> "); |
[Note] the XMLHTTPRequest object is designed to process responses composed of common text or XML. However, a response may also be of another type if the user agent (UA) this content type is supported.
When the Request status changes, the XMLHTTPRequest object calls the event processor registered with onreadystatechange. Therefore, before processing the response, your event processor should first check the value of readystate and HTTP status. When the request is loaded (the value of readystate is 4) and the response is completed (the HTTP status is "OK"), you can call a JavaScript function to process the response content. The following script checks the corresponding values when the response is complete and calls a processresponse () method.
Function processrequest (){ If (xmlhttpreq. readystate = 4 ){ If (xmlhttpreq. Status = 200 ){ Processresponse (); } } } |
The processresponse () method uses the responsexml and responsetext attributes of the XMLHTTPRequest object to retrieve HTTP responses. As explained above, this responsexml is only available when the response media type is text/XML, application/XML, or ends with + XML. This responsetext property will return a response in the form of plain text. For an XML response, you will retrieve the content as follows:
VaR MSG = xmlhttpreq. responsexml; |
With the help of XML stored in the MSG variable, you can use the DOM method getelementsbytagname () to retrieve the value of this element:
VaR catalogid = msg. getelementsbytagname ("catalogid") [0]. firstchild. nodevalue; |
Finally, by updating the HTML content in the validationmessage Div on the web page and using the innerhtml attribute, you can test the element value to create a message to be displayed:
If (catalogid = "valid "){ VaR validationmessage = Document. getelementbyid ("validationmessage "); Validationmessage. innerhtml = "catalog ID is valid "; } Else { VaR validationmessage = Document. getelementbyid ("validationmessage "); Validationmessage. innerhtml = "catalog ID is not valid "; } |
Vi. Summary
The above is the implementation of all the details used by the XMLHTTPRequest object. The XMLHTTPRequest object provides a dynamic interaction between the client and the server by transmitting data without having to send web pages to the server. You can use JavaScript to start a request and process the returned values, and then use the DOM method of the browser to update the data on the page.