前言:
本文摘自《JavaScript.The.Definitive.Guide,5th.Edition》之XMLHttpRequest对象,作为参考资料。
一、XMLHttpRequest对象详解
An HTTP request and response: Firefox 1.0, Internet Explorer 5.0, Safari 1.2,Opera7.60: Object
1. Constructor
new XMLHttpRequest() // All browsersexcept IE 5 and IE 6
new ActiveXObject("Msxml2.XMLHTTP") // IE
new ActiveXObject("Microsoft.XMLHTTP") // IE with older system libraries
2. Properties
readonly short readyState
The state of the HTTP request. The value of this property begins at 0 when anXMLHttpRequest is first created and increases to 4 when the complete HTTPresponse has been received. Each of the five states has an informal name associated with it, and the table below lists the states, their names, and their meanings:
State | Name | Description |
0 | Uninitialized | This is the initial state. The XMLHttpRequest object has just been created or has been reset with the abort( ) method. |
1 | Open | The open( ) method has been called, but send( ) has not. The request has not yet been sent. |
2 | Sent | The send( ) method has been called, and the HTTP request has been transmitted to the web server. No response has been received yet. |
3 | Receiving | All response headers have been received. The response body is being received but is not complete. |
4 | Loaded | The HTTP response has been fully received. |
Thevalue of readyState never decreases, unless abort( ) or open( ) are called on arequest that is already in progress. Every time the value of this propertyincreases, the onreadystatechange event handler is triggered.
readonly String responseText
The body of the response (not including headers) that has been received from theserver so far, or the empty string if no data has been received yet. IfreadyState is less than 3, this property is the empty string. When readyState is 3, this property returns whatever portion of the response has been received so far. If readyState is 4, this property holds the complete body of theresponse.
Ifthe response includes headers that specify a character encoding for the body,that encoding is used. Otherwise, the Unicode UTF-8 encoding is assumed.
readonly Document responseXML
The response to the request, parsed as XML and returned as a Document object. Thisproperty will be null unless all three of the following conditions are true:
- readyState is 4.
- The response includes a Content-Type header of "text/xml", "application/xml", or anything ending with "+xml" to indicate that the response is an XML document.
- The response body consists of well-formed XML markup that can be parsed without errors.
readonly short status
The HTTP status code returned by the server, such as 200 for success and 404 for"Not Found" errors. Reading this property when readyState is lessthan 3 causes an exception.
readonly String statusText
This property specifies the HTTP status code of the request by name rather than by number. That is, it is "OK" when status is 200 and "NotFound" when status is 404. As with the status property, reading thisproperty when readyState is less than 3 causes an exception.
3. Methods
abort()
Cancelsthe current request, closing connections and stopping any pending networkactivity.
getAllResponseHeaders()
Returnsthe HTTP response headers as an unparsed string.
getResponseHeader()
Returns the value of a named HTTP response header
open()
InitializesHTTP request parameters, such as the URL and HTTP method, but does not send therequest.
send()
Sendsthe HTTP request, using parameters passed to the open( ) method and an optionalrequest body passed to this method.
setRequestHeader()
Setsor adds an HTTP request header to an open but unsent request.
4. Event Handlers
onreadystatechange
Event-handlerfunction invoked each time the readyState property changes. It may also beinvoked multiple times while readyState is 3.
5. Description
The XMLHttpRequest object allows client-side JavaScript to issue HTTP requests and receive responses (which need not be XML) from web servers. XMLHttpRequest is the subject of Chapter20, and that chapter contains many examples of its use.
XMLHttpRequest isquite portable and well supported by all modern browsers. The only browserdependency involves the creation of an XMLHttpRequest object. In InternetExplorer 5 and 6, you must use the IE-specific ActiveXObject( ) constructor, asshown in the Constructor section earlier.
Once anXMLHttpRequest object has been created, you typically use it like this:
- Call open( ) to specify the URL and method (usually "GET" or "POST") for the request. When you call open( ), you also specify whether you want the request to be synchronous or asynchronous.
- If you specified an asynchronous request, set the onreadystatechange property to the function that will be notified of the progress of the request.
- Call setRequestHeader( ), if needed, to specify additional request parameters.
- Call send( ) to send the request to the web server. If it is a POST request, you may also pass a request body to this method. If you specify a synchronous request in your call to open( ), the send( ) method blocks until the response is complete and readyState is 4. Otherwise, your onreadystatechange event-handler function must wait until the readyState property reaches 4 (or at least 3).
- Once send( ) has returned for synchronous requests, or readyState has reached 4 for asynchronous requests, you can use the server's response. First, check the status code to ensure that the request was successful. If so, use geTResponseHeader( ) or geTResponseHeaders( ) to retrieve values from the response header, and use the responseText or responseXML properties to obtain the response body.
The XMLHttpRequest object has not been standardized, but work on a standard has begun at the W3Cat the time of this writing. This documentation is based on working drafts ofthe standard. Current XMLHttpRequest implementations are quite interoperable butdiffer in minor ways from the standard. An implementation might return nullwhere the standard requires the empty string, for example, or might setreadyState to 3 without guaranteeing that all response headers are available.
|
|
25.321. XMLHttpRequest.abort( ): cancel an HTTPrequest
25.321.1. Synopsis
void abort( )
25.321.2. Description
This method resetsthe XMLHttpRequest object to a readyState of 0 and aborts any pending networkactivity. You might call this method, for example, if a request has taken toolong, and the response is no longer necessary.
二、xhr对象方法详解
XMLHttpRequest.getAllResponseHeaders( ):return unparsed HTTP response headers
25.322.1. Synopsis
StringgetAllResponseHeaders( )
25.322.1.1. Returns
If readyState is lessthan 3, this method returns null. Otherwise, it returns all HTTP responseheaders (but not the status line) sent by the server. The headers are returnedas a single string, with one header per line. Lines are delimited by "\r\n"line terminators.
25.323. XMLHttpRequest.getResponseHeader( ): get thevalue of a named HTTP response header
25.323.1. Synopsis
StringgetResponseHeader(String header)
25.323.1.1. Arguments
header
Thename of the HTTP response header whose value is to be returned. You may specifythis header name using any case: the comparison to response headers iscase-insensitive.
25.323.1.2. Returns
The value of thenamed HTTP response header, or the empty string if no such header was receivedor if readyState is less than 3. If more than one header with the specifiedname is received, the values of those headers are concatenated and returned,using a comma and space as the delimiter.
25.325. XMLHttpRequest.open( ): initialize HTTPrequest parameters
25.325.1. Synopsis
void open(String method,
String url,
boolean async,
String username, String password)
25.325.1.1. Arguments
method
TheHTTP method to be used for the request. Reliably implemented values includeGET, POST, and HEAD. Implementations may also support methods as well.
url
TheURL that is the subject of the request. Most browsers impose a same-originsecurity policy (see Section13.8.2) and require that this URL have the same hostname and port as thedocument that contains the script. Relative URLs are resolved in the normalway, using the URL of the document that contains the script.
async
Whetherthe request should be performed asynchronously or not. If this argument isfalse, the request is synchronous, and a subsequent call to send( ) will blockuntil the response is fully received. If this argument is true or is omitted,the request is asynchronous, and an onreadystatechange event handler istypically required.
username, password
Theseoptional arguments specify authorization credentials for use with URLs thatrequire authorization. If specified, they override any credentials specified inthe URL itself.
25.325.2. Description
This methodinitializes request parameters for later use by the send( ) method. It setsreadyState to 1; deletes any previously specified request headers andpreviously received response headers; and sets the responseText, responseXML,status, and statusText properties to their default values. It is safe to callthis method when readyState is 0 (when the XMLHttpRequest object is justcreated, or after a call to abort( )) and when readyState is 4 (after aresponse has been received). The behavior of open( ) is unspecified when it iscalled from any other state.
Other than storingrequest parameters for use by send( ) and resetting the XMLHttpRequest objectfor reuse, the open( ) method has no other behavior. In particular, note thatimplementations do not typically open a network connection to the web server whenthis method is called.
25.325.3. See Also
XMLHttpRequest.send(); Chapter20
25.326. XMLHttpRequest.send( ): send an HTTP request
25.326.1. Synopsis
void send(Object body)
25.326.1.1. Arguments
body
Ifthe HTTP method specified by the call to open( ) is "POST" or"PUT", this argument specifies the body of the request, as a stringor Document object, or null if no body is necessary. For any other method, thisargument is unused and should be null. (Some implementations do not allow youto omit this argument.)
25.326.2. Description
This method causes anHTTP request to be issued. If there has been no previous call to open( ), or,more generally, if readyState is not 1, send( ) tHRows an exception. Otherwise,it issues an HTTP request that consists of:
- The HTTP method, URL, and authorization credentials (if any) specified in the previous call to open( )
- The request headers, if any, specified by previous calls to setRequestHeader( )
- The body argument passed to this method
Once the request hasbeen issued, send( ) sets readyState to 2 and triggers the onreadystatechangeevent handler.
If the async argument to the previous call to open( )was false, this method blocks and does not return until readyState is 4 and theserver's response has been fully received. Otherwise, if the async argument istrue or if that argument is omitted, send( ) returns immediately, and theserver's response is processed, as described next, on a background thread.
If the serverresponds with an HTTP redirect, the send( ) method or the background threadfollow the redirect automatically. When all HTTP response headers have beenreceived, send( ) or the background thread sets readyState to 3 and triggersthe onreadystatechange event handler. If the response is long, send( ) or thebackground thread may trigger the onreadystatechange more than once while instate 3: this can serve as a download progress indicator. Finally, when theresponse is complete, send( ) or the background thread sets readyState to 4 andtriggers the event handler one last time.
25.326.3. See Also
XMLHttpRequest.open(); Chapter20
25.327. XMLHttpRequest.setRequestHeader( ): add a HTTPrequest header to the request
25.327.1. Synopsis
voidsetRequestHeader(String name, String value)
25.327.1.1. Arguments
name
Thename of the header to be set. This argument should not contain spaces, colons,linefeeds, or newlines.
value
Thevalue for the header. This argument should not contain linefeeds or newlines.
25.327.2. Description
setRequestHeader( )specifies an HTTP request header that should be included in the request issuedby a subsequent call to send( ). This method may be called only when readyStateis 1i.e., after a call to open( ) but before a call to send( ).
If a header with thespecified name has already beenspecified, the new value for that header is the previously specified value,plus a comma, a space, and the valuespecified in this call.
If the call to open() specifies authorization credentials, XMLHttpRequest automatically sends anappropriate Authorization request header. You can append to this header withsetRequestHeader( ), however. Similarly, if the web browser has stored cookies associatedwith the URL passed to open( ), appropriate Cookie or Cookie2 headers areautomatically included with the request. You can append additional cookies tothese headers by calling setRequestHeader( ). XMLHttpRequest may also provide adefault value for the User-Agent header. If it does this, any value you specifyfor that header is appended to the default value.
Some request headersare automatically set by the XMLHttpRequest for conformance to the HTTPprotocol and may not be set with this method. These include proxy-relatedheaders as well as the following:
Host
Connection
Keep-Alive
Accept-Charset
Accept-Encoding
If-Modified-Since
If-None-Match
If-Range
Range
25.327.3. See Also
XMLHttpRequest.getResponseHeader( )
|
|
25.324. XMLHttpRequest.onreadystatechange: eventhandler function invoked when readyState changes
25.324.1. Synopsis
Functiononreadystatechange
25.324.2. Description
This propertyspecifies an event-handler function that is invoked each time the readyStateproperty changes. It may also be invoked (but this is not required) multipletimes while readyState is 3 to provide notification of download progress.
An onreadystatechangehandler typically checks the readyState of the XMLHttpRequest object to see ifit has reached 4. If so, it does something with the responseText or responseXMLproperties.
It is unspecifiedwhether any arguments will be passed to the function. In particular, there isno standard way for the event-handler function to get a reference to theXMLHttpRequest object it is registered on. This means that it is not possibleto write a generic handler function that can be used for multiple requests.
The XMLHttpRequestobject is supposed to follow the DOM event model and implement anaddEventListener( ) method for registering handlers for readystatechangeevents. (See Event.addEventListener( ), for example.) Since IE does not supportthe DOM event model, and since it is rare to require more than one eventhandler per request, it is safer to simply assign a single handler function toonreadystatechange.
附注:
ajax和新对象XMLHttpRequest所有api如上,如有错漏,烦请指正,不胜感激!