CARVIEW |
The XMLHttpRequest
Object
W3C Working Draft 15 April 2008
- This Version:
- https://www.w3.org/TR/2008/WD-XMLHttpRequest-20080415/
- Latest Version:
- https://www.w3.org/TR/XMLHttpRequest/
- Previous Versions:
- https://www.w3.org/TR/2007/WD-XMLHttpRequest-20071026/
- https://www.w3.org/TR/2007/WD-XMLHttpRequest-20070618/
- https://www.w3.org/TR/2007/WD-XMLHttpRequest-20070227/
- https://www.w3.org/TR/2006/WD-XMLHttpRequest-20060927/
- https://www.w3.org/TR/2006/WD-XMLHttpRequest-20060619/
- https://www.w3.org/TR/2006/WD-XMLHttpRequest-20060405/
- https://www.w3.org/TR/2007/WD-XMLHttpRequest-20070618/
- Editor:
- Anne van Kesteren (Opera Software ASA) <annevk@opera.com>
Copyright © 2007 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.
Abstract
The XMLHttpRequest
Object specification defines an
API that provides
scripted client functionality for transferring data between a client and a
server.
Status of this Document
This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at https://www.w3.org/TR/.
This is the 15 April 2008 Last Call Working Draft of The XMLHttpRequest
Object specification. Please send comments
to public-webapi@w3.org (archived)
with either [XHR] or [XMLHttpRequest]
at the start of the subject line before befor 2 June 2008.
This document is produced by the Web API Working Group, part of the Rich Web Clients Activity in the W3C Interaction Domain. Changes made to this document can be found in the W3C public CVS server.
Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.
This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.
Table of Contents
- 1. Introduction
- 2. Conformance
- 3. Security Considerations
- 4. The
XMLHttpRequest
Object - Not in this Specification
- References
- Acknowledgments
1. Introduction
This section is non-normative.
The XMLHttpRequest
object implements an interface exposed by a scripting engine that allows
scripts to perform HTTP client functionality, such as submitting form data
or loading data from a server.
The name of the object is XMLHttpRequest
for compatibility
with the Web, though each component of this name is potentially
misleading. First, the object supports any text based format, including
XML. Second, it can be used to make requests over both HTTP and HTTPS
(some implementations support protocols in addition to HTTP and HTTPS, but
that functionality is not covered by this specification). Finally, it
supports "requests" in a broad sense of the term as it pertains to HTTP;
namely all activity involved with HTTP requests or responses for the
defined HTTP methods.
Some simple code to do something with data from an XML document fetched over the network:
function test(data) {
// taking care of data
}
function handler() {
if(this.readyState == 4 && this.status == 200) {
// so far so good
if(this.responseXML != null && this.responseXML.getElementById('test').firstChild.data)
// success!
test(this.responseXML.getElementById('test').firstChild.data);
else
test(null);
} else if (this.readyState == 4 && this.status != 200) {
// fetched the wrong page or network error...
test(null);
}
}
var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("GET", "test.xml");
client.send();
If you just want to log a message to the server:
function log(message) {
var client = new XMLHttpRequest();
client.open("POST", "/log");
client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
client.send(message);
}
Or if you want to check the status of a document on the server:
function fetchStatus(address) {
var client = new XMLHttpRequest();
client.onreadystatechange = function() {
// in case of network errors this might not give reliable results
if(this.readyState == 4)
returnStatus(this.status);
}
client.open("HEAD", address);
client.send();
}
2. Conformance
Everything in this specification is normative except for diagrams, examples, notes and sections marked non-normative.
The key words must, must not, should and may in this document are to be interpreted as described in RFC 2119. [RFC2119]
This specification defines the following classes of products:
- Conforming user agent
-
A user agent must behave as described in this specification in order to be considered conformant.
If the user agent is not a conforming XML user agent the XML response entity body must (always) be
null
.User agents may implement algorithms given in this specification in any way desired, so long as the end result is indistinguishable from the result that would be obtained by the specification's algorithms.
This specification uses both the terms "conforming user agent(s)" and "user agent(s)" to refer to this product class.
- Conforming XML user agent
-
An XML user agent must be a conforming user agent and must be a conforming XML processor that reports violations of namespace well-formedness. [XML] [XMLNS]
2.1 Dependencies
This specification relies on several underlying specifications.
- DOM
-
A conforming user agent must support some subset of the functionality defined in DOM Events and DOM Core that this specification relies upon. [DOM2Events] [DOM3Core]
- HTML 5
-
This specification depends on HTML 5 for defining the
Window
object and finding the character encoding of atext/html
resource. A conforming user agent must support these features. [HTML5]The Window Object 1.0 draft is not referenced normatively as it appears to be no longer maintained and HTML 5 defines the
Window
object in more detail. This specification already depends on HTML 5 for other reasons so there is not much additional overhead because of this. - HTTP
-
A conforming user agent must support some version of the HTTP protocol. It should support any HTTP method that matches the
Method
production and must at least support the following methods:GET
POST
HEAD
PUT
DELETE
OPTIONS
Other requirements regarding HTTP are made throughout the specification. [RFC2616]
2.2 Terminology
There is a case-insensitive match of strings s1 and s2 if after mapping the ASCII character range A-Z to the range a-z both strings are identical.
Two URIs are same-origin if after performing scheme-based normalization on both URIs as described in section 5.3.3 of RFC 3987 the scheme, ihost and port components are identical. If either URI does not have an ihost component the URIs must not be considered same-origin. [RFC3987]
The terms origin and event handler DOM attribute are defined by the HTML 5 specification. [HTML5]
2.3 Extensibility
Extensions of the API defined by this specification are strongly discouraged. User agents, Working Groups and other interested parties should discuss extensions on a relevant public forum, preferably public-webapi@w3.org.
3. Security Considerations
Apart from requirements affecting security made throughout this specification implementations may, at their discretion, not expose certain headers, such as HttpOnly cookies.
4. The XMLHttpRequest
Object
The XMLHttpRequest
object can be used by scripts to programmatically connect to their
originating server via HTTP.
Objects implementing the XMLHttpRequest
interface must also implement the EventTarget
interface.
[DOM2Events]
Objects implementing the Window
interface must provide an XMLHttpRequest()
constructor. [HTML5]
In ECMAScript this can be used as follows:
var client = new XMLHttpRequest();
When the XMLHttpRequest()
constructor is invoked a
persistent pointer to the associated Document
object
is stored on the newly created object. This is the Document
pointer. The associated Document
object is the one
returned by the document
attribute from the object on which
the XMLHttpRequest()
constructor was invoked (a
Window
object). The pointer can become "null" if the object
is destroyed.
As per the conformance criteria implementations are free to implement this in any way they desire as long as the end results are identical to those given by the English prose.
If iframe
is a Window
object client
will have a pointer to
iframe.document
in the following example:
var client = new iframe.XMLHttpRequest()
interface XMLHttpRequest { // event handler attribute EventListener onreadystatechange; // state const unsigned short UNSENT = 0; const unsigned short OPENED = 1; const unsigned short HEADERS_RECEIVED = 2; const unsigned short LOADING = 3; const unsigned short DONE = 4; readonly attribute unsigned short readyState; // request void open(in DOMString method, in DOMString url); void open(in DOMString method, in DOMString url, in boolean async); void open(in DOMString method, in DOMString url, in boolean async, in DOMString user); void open(in DOMString method, in DOMString url, in boolean async, in DOMString user, in DOMString password); void setRequestHeader(in DOMString header, in DOMString value); void send(); void send(in DOMString data); void send(in Document data); void abort(); // response DOMString getAllResponseHeaders(); DOMString getResponseHeader(in DOMString header); readonly attribute DOMString responseText; readonly attribute Document responseXML; readonly attribute unsigned short status; readonly attribute DOMString statusText; };
The XMLHttpRequest
object can be in five states: UNSENT, OPENED, HEADERS_RECEIVED, LOADING and DONE. The current state is
exposed through the readyState
attribute. The method definitions below define when a state transition
takes place.
When constructed, the XMLHttpRequest
object must be in the UNSENT state. This state is represented by
the UNSENT
constant, whose value is 0
.
The OPENED state is the state of the object when the open()
method has been successfully invoked.
During this state request headers can be set using setRequestHeader()
and the request can
be made using send()
. This state is
represented by the OPENED
constant, whose value is 1
.
The OPENED state has an associated send()
flag which can be either "true" or "false". The initial value of the
send()
flag is "false".
The HEADERS_RECEIVED state is the state of the object when all response
headers have been received. This state is represented by the HEADERS_RECEIVED
constant, whose value is
2
.
The LOADING state is the state of the object when the response entity
body is being received. This state is represented by the LOADING
constant, whose value is 3
.
The DONE state is the state of the object when either the data transfer
has been completed or something went wrong during the transfer (infinite
redirects for instance). This state is represented by the DONE
constant, whose
value is 4
.
The DONE state has an associated error flag which can be either "true" or "false". The initial value of the error flag is "false".
The response entity body is the fragment of the entity body received so far (LOADING state) or the complete entity body (DONE state). If there is no entity body the response entity body is "null".
The text response entity body is
a DOMString
representing the response entity body. The text response
entity body is the return value of the following algorithm:
-
If the response entity body is "null" return the empty string and terminate these steps.
-
Let charset be "null".
-
If there is no
Content-Type
header or there is aContent-Type
header which contains a MIME type that istext/xml
,application/xml
or ends in+xml
(ignoring any parameters) use the rules set forth in the XML specifications to determine the character encoding. Let charset be the determined character encoding. -
If there is a
Content-Type
header which contains atext/html
MIME type follow the rules set forth in the HTML 5 specification to determine the character encoding. Let charset be the determined character encoding. [HTML5] -
If the MIME type specified by the
Content-Type
header contains acharset
parameter and charset is "null" let charset be the value of that parameter.The algorithms described by the XML and HTML specifications already take
Content-Type
into account. -
If charset is "null" then, for each of the rows in the following table, starting with the first one and going down, if the first bytes of bytes match the bytes given in the first column, then let charset be the encoding given in the cell in the second column of that row. If there is no match charset remains "null".
Bytes in Hexadecimal Description 00 00 FE FF UTF-32BE BOM FF FE 00 00 UTF-32LE BOM FE FF UTF-16BE BOM FF FE UTF-16LE BOM EF BB BF UTF-8 BOM -
If charset is "null" let charset be UTF-8.
-
Return the result of decoding the response entity body using charset. Replace bytes or sequences of bytes that are not valid accordng to the charset with a single U+FFFD character.
Authors are encouraged to simply encode their resources using UTF-8.
The XML response entity body is
either a Document
representing the response entity body or
null
. The XML response entity body is the return value of the
following algorithm:
-
If the response entity body is "null" terminate these steps and return
null
. -
If a
Content-Type
is present and it does not contain a MIME type (ignoring any parameters) that istext/xml
,application/xml
or ends in+xml
terminate these steps and returnnull
. (Do not terminate these steps if there is noContent-Type
header at all.) -
Parse the response entity body into a document tree following the rules from the XML specifications. Let the result be parsed document. If this fails (unsupported character encoding, namespace well-formedness error et cetera) terminate these steps return
null
. [XML] [XMLNS]Scripts in the resulting document tree will not be executed, resources referenced will not be loaded and no associated XSLT will be applied.
-
Return an object implementing the
Document
interface representing the parsed document.
onreadystatechange
of typeEventListener
-
This attribute is an event handler DOM attribute and must be invoked whenever a
readystatechange
event is targated at the object. readyState
of typeunsigned short
, readonly-
On getting the attribute must return the value of the constant corresponding to the object's current state.
open(method, url, async, user, password)
, method-
When invoked, the user agent must follow the following steps (unless otherwise indicated):
-
Let stored method be the method argument.
-
If stored method does not match the
Method
production, defined in section 5.1.1 of RFC 2616, raise aSYNTAX_ERR
exception and terminate these steps. [RFC2616] -
If stored method case-insensitively matches
CONNECT
,DELETE
,GET
,HEAD
,OPTIONS
POST
,PUT
,TRACE
, orTRACK
let stored method be the canonical uppercase form of the matched method name. -
If stored method is one of
CONNECT
,TRACE
, orTRACK
the user agent should raise aSECURITY_ERR
exception and terminate these steps. -
Drop the fragment identifier (if any) from url and let stored url be the result of that operation.
-
If stored url is a relative reference resolve it using the current value of the
baseURI
attribute of theDocument
pointer. If this fails raise aSYNTAX_ERR
exception and terminate these steps. -
If stored url contains an unsupported scheme raise a
NOT_SUPPORTED_ERR
and terminate these steps. -
If the
"user:password"
format in theuserinfo
production defined in section 3.2.1 of RFC 3986 is not supported for the relevant scheme and stored url contains this format raise aSYNTAX_ERR
and terminate these steps. [RFC3986] -
If stored url contains the
"user:password"
format let stored user be the user part and stored password be the password part. -
If stored url just contains the
"user"
format let stored user be the user part. -
If stored url is not of the same-origin as the origin of the
Document
pointer the user agent should raise aSECURITY_ERR
exception and terminate these steps. -
Let async be the value of the async argument or
true
if it was omitted. -
If the user argument was not omitted, and its syntax does not match that specified by the relevant authentication scheme, raise a
SYNTAX_ERR
exception and terminate these steps. -
If the user argument was not omitted and is not
null
let stored user be user encoded using the encoding specified in the relevant authentication scheme or UTF-8 if the scheme fails to specify an encoding.This step overrides any user that may have been set by the url argument.
-
If the user argument was not omitted and is
null
remove stored user. -
If the password argument was not omitted and its syntax does not match that specified by the relevant authentication scheme raise a
SYNTAX_ERR
exception and terminate these steps. -
If the password argument was not omitted and is not
null
let stored password be password encoded using the encoding specified in the relevant authentication scheme or UTF-8 if the scheme fails to specify an encoding. -
If the password argument was not omitted and is
null
remove stored password. -
Abort the
send()
algorithm, set response entity body to "null" and reset the list of request headers. -
The user agent should cancel any network activity for which the object is responsible.
-
Switch the object to the OPENED state, set the
send()
flag to "false" and then synchronously dispatch areadystatechange
event on the object and return the method call.
A future version or extension of this specification will most likely define a way of doing cross-site requests.
-
setRequestHeader(header, value)
, method-
Each request has a list of request headers with associated values. The
setRequestHeader()
method can be used to manipulate those values and set new request headers.The
setRequestHeader()
method appends a value if the HTTP header given as argument is already part of the list of request headers.When invoked, the user agent must follow the following steps (unless otherwise indicated):
-
If the state of the object is not OPENED raise an
INVALID_STATE_ERR
exception and terminate these steps. -
If the
send()
flag is "true" raise anINVALID_STATE_ERR
exception and terminate these steps. -
If the header argument does not match the
field-name
production as defined by section 4.2 of RFC 2616 or isnull
raise aSYNTAX_ERR
exception and terminate these steps. [RFC2616] -
If the value argument is
null
terminate these steps. (Do not raise an exception.) -
If the value argument does not match the
field-value
production as defined by section 4.2 of RFC 2616 raise aSYNTAX_ERR
and terminate these steps. [RFC2616] -
For security reasons, these steps should be terminated if the header argument case-insensitively matches one of the following headers:
Accept-Charset
Accept-Encoding
Connection
Content-Length
Content-Transfer-Encoding
Date
Expect
Host
Keep-Alive
Referer
TE
Trailer
Transfer-Encoding
Upgrade
Via
-
Also for security reasons, these steps should be terminated if the start of the header argument case-insensitively matches
Proxy-
orSec-
. -
If the header argument is not in the list of request headers append the header with its associated value to the list and terminate these steps.
-
If the header argument is in the list of request headers either use multiple headers, combine the values or use a combination of those (section 4.2, RFC 2616). [RFC2616]
See also the
send()
method regarding user agent header handling for caching, authentication, proxies, and cookies.// The following script: var client = new XMLHttpRequest(); client.open('GET', 'demo.cgi'); client.setRequestHeader('X-Test', 'one'); client.setRequestHeader('X-Test', 'two'); client.send(); // ...would result in the following header being sent: ... X-Test: one, two ...
-
send(data)
, method-
The
send()
method initiates the request and its optional argument provides the entity body.Authors are encouraged to ensure that they have specified the
Content-Type
header viasetRequestHeader()
before invokingsend()
with a non-null
data argument.When invoked, the user agent must follow the following steps (unless otherwise noted). Note that this algorithm might get aborted if the
open()
orabort()
method is invoked. When thesend()
algorithm is aborted the user agent must terminate the algorithm after finishing the step it is on.The following algorithm can not be aborted through script when async is
false
. It can only be aborted when async istrue
and only after the method call has returned.-
If the state of the object is not OPENED raise an
INVALID_STATE_ERR
exception and terminate these steps. -
If the
send()
flag is "true" raise anINVALID_STATE_ERR
exception and terminate these steps. -
If async is
true
set thesend()
flag to "true". -
If stored method is
GET
act as if the data argument isnull
.If the data argument has not been omitted and is not
null
use it for the entity body as defined by section 7.2 of RFC 2616 observing the following rules: [RFC2616]- data is a
DOMString
-
Encode data using UTF-8 for transmission.
If a
Content-Type
header is set usingsetRequestHeader()
set thecharset
parameter of that header toUTF-8
. - data is a
Document
-
Serialize data into a namespace well-formed XML document and encoded using the encoding given by
data.inputEncoding
, when notnull
, or UTF-8 otherwise. Or, if this fails because theDocument
cannot be serialized act as if data isnull
.If no
Content-Type
header has been set usingsetRequestHeader()
append aContent-Type
header to the list of request headers with a value ofapplication/xml;charset=charset
where charset is the encoding used to encode the document.Subsequent changes to the
Document
have no effect on what is submitted. - data is not a
DOMString
orDocument
-
Use the stringification mechanisms of the host language on data and treat the result as if data is a
DOMString
. Or, if this fails, act as if the data argument isnull
.
If the data argument has been omitted, or is
null
, no entity body is used in the request. - data is a
-
Make a request to stored url, using HTTP method stored method, user stored user (if provided) and password stored password (if provided), taking into account the entity body, list of request headers and the rules listed directly after this set of steps.
-
Synchronously dispatch a
readystatechange
event on the object.The state of the object does not change. The event is dispatched for historical reasons.
-
If async is
true
return thesend()
method call. (Do not terminate the steps in the algorithm though.) -
While downloading the resource the following rules are to be observed.
- If the response is an HTTP redirect
-
If the redirect does not violate security (it is same-origin for instance) or infinite loop precautions and the scheme is supported transparently follow the redirect and go to the start of this step (step 8).
HTTP places requirements on the user agent regarding the preservation of the request method and entity body during redirects, and also requires users to be notified of certain kinds of automatic redirections.
Otherwise, follow the following set of steps:
-
Set the response entity body to "null", the error flag to "true" and reset the list of request headers.
-
Synchronously switch the state to DONE.
-
If async is set to
false
raise aNETWORK_ERR
exception and terminate the overall algorithm. -
Synchronously dispatch a
readystatechange
event on the object. -
Terminate the overall algorithm.
It is likely that a future version of the
XMLHttpRequest
object will dispatch anerror
event here as well. -
- If the user cancels the download
-
Run the following set of steps:
-
Set the response entity body to "null", the error flag to "true" and reset the list of request headers.
-
Synchronously switch the state to DONE.
-
If async is set to
false
raise anABORT_ERR
exception and terminate the overall algorithm. -
Synchronously dispatch a
readystatechange
event on the object. -
Terminate the overall algorithm.
It is likely that a future version of the
XMLHttpRequest
object will dispatch anabort
event here as well. -
- In case of network errors
-
In case of DNS errors, or other type of network errors, run the following set of steps. This does not include HTTP responses that indicate some type of error, such as HTTP status code 410.
-
Set the response entity body to "null", the error flag to "true" and reset the list of request headers.
-
Synchronously switch the state to DONE.
-
If async is set to
false
raise aNETWORK_ERR
exception and terminate the overall algorithm. -
Synchronously dispatch a
readystatechange
event on the object. -
Terminate the overall algorithm.
It is likely that a future version of the
XMLHttpRequest
object will dispatch anerror
event here as well. -
- Once all HTTP headers have been received
-
If all HTTP headers have been received, before receiving the message body (if any), run the following steps:
-
Synchronously switch the state to HEADERS_RECEIVED.
-
Synchronously dispatch a
readystatechange
event on the object.
-
- Once the first byte (or more) of the response entity body has been
received
- If there is no response entity body
-
-
Synchronously switch the state to LOADING.
-
Synchronously dispatch a
readystatechange
event on the object.
-
Finally, once the complete resource has been downloaded go to the next step.
-
When the request has successfully completed loading, synchronously switch the state to DONE and then synchronously dispatch a
readystatechange
event on the object and return the method call in case of async beingfalse
.
If the user agent allows the user to configure a proxy it should modify the request appropriately; i.e., connect to the proxy host instead of the origin server, modify the
Request-Line
and sendProxy-Authorization
headers as specified.If the user agent supports HTTP Authentication it should consider requests originating from this object to be part of the protection space that includes the accessed URIs and send
Authorization
headers and handle401 Unauthorized
requests appropriately. If authentication fails, user agents should prompt the users for credentials. [RFC2617]If the user agent supports HTTP State Management it should persist, discard and send cookies (as received in the
Set-Cookie
andSet-Cookie2
response headers, and sent in theCookie
header) as applicable. [RFC2965]If the user agent implements a HTTP cache it should respect
Cache-Control
request headers set by the script (e.g.,Cache-Control: no-cache
bypasses the cache). It must not sendCache-Control
orPragma
request headers automatically unless the user explicitly requests such behavior (e.g., by (force-)reloading the page).304 Not Modified
responses that are a result of a user agent generated conditional request must be presented as200 OK
responses with the appropriate content. The user agent must allow scripts to override automatic cache validation by setting request headers (e.g.,If-None-Match
,If-Modified-Since
), in which case304 Not Modified
responses must be passed through. [RFC2616]If the user agent implements server-driven content-negotiation it should set
Accept-Encoding
andAccept-Charset
headers as appropriate; it must not automatically set theAccept
. If theAccept-Language
header is not set usingsetRequestHeader()
user agents should provide it. Responses to such requests must have the content-encodings automatically decoded. [RFC2616] -
abort()
, method-
When invoked, the user agent must run the following steps (unless otherwise noted):
-
Abort the
send()
algorithm, set the response entity body to "null", the error flag to "true" and remove any registered request headers. -
The user agent should cancel any network activity for which the object is responsible.
-
If the state is UNSENT, OPENED and the
send()
flag is "false", or DONE go to the next step.Otherwise, switch the state to DONE, set the
send()
flag to "false" and synchronously dispatch areadystatechange
event on the object. -
Switch the state to UNSENT. (Do not dispatch the
readystatechange
event.)It is likely that a future version of the
XMLHttpRequest
object will dispatch anabort
event here as well.
-
getAllResponseHeaders()
, method-
When invoked, the user agent must run the following steps:
-
If the state is UNSENT or OPENED raise an
INVALID_STATE_ERR
exception and terminate these steps. -
If the error flag is "true" return the empty string and terminate these steps.
-
Return all the HTTP headers, as a single string, with each header line separated by a U+000D (CR) U+000A (LF) pair excluding the status line.
// The following script: var client = new XMLHttpRequest(); client.open("GET", "test.txt", true); client.send(); client.onreadystatechange = function() { if(this.readyState == 3) { print(this.getAllResponseHeaders()); } } // ...should output something similar to the following text: Date: Sun, 24 Oct 2004 04:58:38 GMT Server: Apache/1.3.31 (Unix) Keep-Alive: timeout=15, max=99 Connection: Keep-Alive Transfer-Encoding: chunked Content-Type: text/plain; charset=utf-8
-
getResponseHeader(header)
, method-
When the method is invoked, the user agent must run the following steps:
-
If the state is UNSENT or OPENED raise an
INVALID_STATE_ERR
exception and terminate these steps. -
If the header argument does not match the
field-name
production returnnull
and terminate these steps. -
If the error flag is "true" return
null
and terminate these steps. -
If the header argument case-insensitively matches multiple HTTP headers for the last request sent, return the values of these headers as a single concatenated string separated from each other by an U+002C followed by an U+0020 character and terminate these steps.
-
If the header argument case-insensitively matches a single HTTP header for the last request sent return the value of that header and terminate these steps.
-
Return
null
.
// The following script: var client = new XMLHttpRequest(); client.open("GET", "test.txt", true); client.send(); client.onreadystatechange = function() { if(this.readyState == 3) { print(client.getResponseHeader("Content-Type")); } } // ...should output something similar to the following text: text/plain; charset=utf-8
-
responseText
of typeDOMString
, readonly-
On getting, the user agent must run the following steps:
-
If the state is not LOADING or DONE return the empty string and terminate these steps.
-
Return the text response entity body.
-
responseXML
of typeDocument
, readonly-
On getting, the user agent must run the following steps:
-
If the state is not DONE return
null
and terminate these steps. -
Return the XML response entity body.
-
status
of typeunsigned short
, readonly-
On getting, if available, it must return the HTTP status code sent by the server (typically
200
for a successful request). Otherwise, if not available, the user agent must raise anINVALID_STATE_ERR
exception. statusText
of typeDOMString
, readonly-
On getting, if available, it must return the HTTP status text sent by the server (appears after the status code). Otherwise, if not available, the user agent must raise an
INVALID_STATE_ERR
exception.
4.1 Events for the XMLHttpRequest
Object
This section describes the various events that can be dispatched on
objects implementing the XMLHttpRequest
interface. For
this version of the specification only one event is defined.
readystatechange
- When the user agent dispatches a
readystatechange
event (as indicated above) it must not bubble, must not be cancelable and must implement theEvent
interface. ItsnamespaceURI
attribute must benull
. [DOM2Events]
4.2 Exceptions for the XMLHttpRequest
Object
Several algorithms in this specification may result in an exception
being thrown. These exceptions are all part of the group
ExceptionCode
and use the DOMException
object
which is defined in DOM Level 3 Core. In addition this specification
extends the ExceptionCode
group with several new constants as
indicated below. [DOM3Core]
const unsigned short SECURITY_ERR = 18; const unsigned short NETWORK_ERR = 101; const unsigned short ABORT_ERR = 102;
The SECURITY_ERR
exception is
raised if an attempt is made to perform an operation or access some data
in a way that would be a security risk or a violation of the user agent's
security policy.
The SECURITY_ERR
exception is expected
to be eventually folded into an update of the the DOM Level 3 Core
specification with an equivalent definition and identical constant value.
Until that happens it is defined here to guide implementors. (This is also
the reason the constant value is not in line with the other exceptions.)
The NETWORK_ERR
exception is
raised when a network error occurs in synchronous requests.
The ABORT_ERR
exception is raised
when the user aborts a request in synchronous requests.
Not in this Specification
This section is non-normative.
This specification does not include the following features which are being considered for a future version of this specification:
load
event andonload
attribute;error
event andonerror
attribute;progress
event andonprogress
attribute;abort
event andonabort
attribute;- Timers have been suggested, perhaps an
ontimeout
attribute; - Property to disable following redirects;
responseXML
fortext/html
documents;- Cross-site
XMLHttpRequest
; responseBody
to deal with byte streams;overrideMimeType
to fix up MIME types;getRequestHeader()
andremoveRequestHeader()
.
References
- [DOM2Events]
- Document Object Model (DOM) Level 2 Events Specification, T. Pixley, editor. W3C, November 2000.
- [DOM3Core]
- Document Object Model (DOM) Level 3 Core Specification, A. Le Hors, P. Le Hégaret, L. Wood, G. Nicol, J. Robie, M. Champion, S. Byrne, editors. W3C, April 2004.
- [ECMAScript]
- ECMAScript Language Specification, Third Edition. ECMA, December 1999.
- [HTML5]
- HTML 5 (work in
progress), I. Hickson, D. Hyatt, editors. W3C, 2008.
- HTML 5 (work in progress), I. Hickson, editor. WHATWG, 2008.
- [RFC2119]
- Key words for use in RFCs to Indicate Requirement Levels, S. Bradner. IETF, March 1997.
- [RFC2616]
- Hypertext Transfer Protocol -- HTTP/1.1, R. Fielding, J. Gettys, J. Mogul, H. Frystyk, L. Masinter, P. Leach, T. Berners-Lee, editors. IETF, June 1999.
- [RFC2617]
- HTTP Authentication: Basic and Digest Access Authentication, P. Hallam-Baker, J. Hostetler, S. Lawrence, P. Leach, A. Luotonen, L. Stewart, editors. IETF, June 1999.
- [RFC2965]
- HTTP State Management Mechanism, D. Kristol, L. Montulli, editors. IETF, October 2000.
- [RFC3986]
- Uniform Resource Identifier (URI): Generic Syntax, T. Berners-Lee, R. Fielding, L. Masinter, editors. IETF, January 2005.
- [RFC3987]
- Internationalized Resource Identifiers (IRIs), M. Duerst, M. Suignard, editors. IETF, January 2005.
- [XML]
- Extensible Markup Language (XML) 1.0 (Fourth Edition), T. Bray, J. Paoli, C. Sperberg-McQueen, E. Maler, F. Yergeau, editors. W3C, September 2006.
- [XMLNS]
- Namespaces in XML (Second Edition), T. Bray, D. Hollander, A. Layman, R. Tobin, editors. W3C, August 2006.
Acknowledgments
The editor would like to thank Addison Phillips, Ahmed Kamel, Alex Hopmann, Alex Vincent, Alexey Proskuryakov, Asbjørn Ulsberg, Boris Zbarsky, Björn Höhrmann, Cameron McCormack, Christophe Jolif, Charles McCathieNevile, Dan Winship, David Håsäther, Dean Jackson, Denis Sureau, Doug Schepers, Douglas Livingstone, Elliotte Harold, Eric Lawrence, Sam Sneddon, Gideon Cohn, Gorm Haug Eriksen, Hallvord R. M. Steen, Håkon Wium Lie, Ian Davis, Ian Hickson, Ivan Herman, Jeff Walden, Jens Lindström, Jim Deegan, Jim Ley, Joe Farro, Jonas Sicking, Julian Reschke, Karl Dubost, Maciej Stachowiak, Magnus Kristiansen, Marc Hadley, Marcos Caceres, Mark Baker, Mark Nottingham, Mohamed Zergaoui, Pawel Glowacki, Robin Berjon, Ruud Steltenpool, Simon Pieters, Stewart Brodie, Sunava Dutta, Tom Magliery and Zhenbin Xu for their contributions to this specification.
Special thanks to the Microsoft employees who first implemented the
XMLHttpRequest
interface, which was first widely
deployed by the Windows Internet Explorer browser.
Special thanks also to the WHATWG for drafting an initial version of this specification in their Web Applications 1.0 document (now renamed to HTML 5). [HTML5]
Thanks also to all those who have helped to improve this specification by sending suggestions and corrections. (Please, keep bugging us with your issues!)