XMLHttpRequest
Level 2Copyright © 2007 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.
XMLHttpRequest
Level 2 enhances XMLHttpRequest
with new features, such as cross-site
requests, progress events, and the handling of byte streams for both
sending and receiving.
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 http://www.w3.org/TR/.
This is the 30 September 2008 Working Draft of XMLHttpRequest
Level 2. Please send comments to public-webapps@w3.org
(archived)
with [XHR2] at the start of the subject line.
In case of conflict with the editor's draft of The
XMLHttpRequest
Object that draft is likely to be more
accurate. Please raise such differences on the public-webapps@w3.org
mailing list taking into account that this draft defines a superset.
This document is produced by the Web Applications (WebApps) Working Group. The WebApps Working Group is part of the Rich Web Clients Activity in the W3C Interaction Domain.
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.
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.
XMLHttpRequest
Object
To be written.
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 a single conformance class:
A user agent must behave as described in this specification in order to be considered conformant.
User agents may optimize any algorithm given in this specification, 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.
This specification relies on several underlying specifications.
A conforming user agent must support the algorithms of the Access Control for Cross-site Requests specification. [AC]
A conforming user agent must support at least
the subset of the functionality defined in DOM Events and DOM Core that
this specification relies upon, such as various exceptions
EventTarget
. [DOM2Events] [DOM3Core]
A conforming user agent must support at least the subset of the functionality
defined in HTML 5 that this specification relies upon, such as the
Window
object and serializing a Document
object. [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.
A conforming user agent must support some version of the HTTP protocol. Requirements regarding HTTP are made throughout the specification. [RFC2616]
A conforming user agent must be a conforming XML processor that reports violations of namespace well-formedness. [XML] [XMLNS]
The terms and algorithms <fragment>, <scheme>, ASCII case-insensitive, converting a string to uppercase, event handler DOM attribute, base URL, origin, same origin, and resolve a URL are defined by the HTML 5 specification. [HTML5]
The term entity body is used as described in
RFC 2616. Method token is used as described in
section 5.1.1 of RFC 2616. field-name
and field-value
are used as described in
section 4.2 of RFC 2616. [RFC2616]
The terms status return flag, url return flag, and cross-site access request are defined by the Access Control for Cross-site Requests specification. [AC]
To dispatch a
readystatechange
event means that an event with the
name readystatechange
,
with no namespace, which does not bubble and is not cancelable, and which
uses the Event
interface, must be
dispatched at the given object.
To dispatch a progress event called e means… [PE]
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.
XMLHttpRequest
ObjectThe XMLHttpRequest
object can be used by scripts to programmatically connect to their
originating server via HTTP.
interface XMLHttpRequestEventTarget : EventTarget {
// event handler attributes
attribute EventListener onabort;
attribute EventListener onerror;
attribute EventListener onload;
attribute EventListener onloadstart;
attribute EventListener onprogress;
};
interface XMLHttpRequestUpload : XMLHttpRequestEventTarget {
// for future use
};
[Constructor] interface XMLHttpRequest : XMLHttpRequestEventTarget {
// event handler attributes
attribute EventListener onreadystatechange;
// ready states
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 metadata
attribute boolean withCredentials;
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, [Null=Null, Undefined=Null] in DOMString user);
void open(in DOMString method, in DOMString url, in boolean async, [Null=Null, Undefined=Null] in DOMString user, [Null=Null, Undefined=Null] in DOMString password);
void setRequestHeader(in DOMString header, in DOMString value);
// request
readonly attribute XMLHttpRequestUpload upload;
void send();
void send(in ByteArray data);
void send([Null=Null, Undefined=Null] in DOMString data);
void send(in Document data);
void abort();
// response metadata
DOMString getAllResponseHeaders();
DOMString getResponseHeader(in DOMString header);
readonly attribute unsigned short status;
readonly attribute DOMString statusText;
// response body
void overrideMimeType(mime);
readonly attribute ByteArray responseBody;
readonly attribute DOMString responseText;
readonly attribute Document responseXML;
};
The EventTarget
interface is defined by the DOM Level 2
Events specification. [DOM2Events]
Objects implementing the Window
interface must provide the following constructor: XMLHttpRequest()
.
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()
The origin of an XMLHttpRequest
object is the
origin of the associated Document
object returned by the Document
pointer.
The event handler attributes listed below must be
supported on objects implementing an interface that inherits from XMLHttpRequestEventTarget
.
Event handler attributes are event handler DOM attributes.
onabort
Must be invoked whenever an abort
event is
targeted at the object.
onerror
Must be invoked whenever an error
event is targeted at the object.
onload
Must be invoked whenever a load
event is targeted at the object.
onloadstart
Must be invoked whenever a loadstart
event is targeted at the
object.
onprogress
Must be invoked whenever a progress
event is targeted at the
object.
The following event handler attribute must be
supported on objects implementing the XMLHttpRequest
interface:
onreadystatechange
Must be invoked whenever a readystatechange
event is
targeted at the object.
The XMLHttpRequest
object can be in several states. The readyState
attribute, on getting, must return the current state of the object, which must be one of the following values:
UNSENT
(numeric value 0)
The object has been constructed.
OPENED
(numeric value 1)
The open()
method has been
successfully invoked. During this state request headers can be set using
setRequestHeader()
and the
request can be made using the send()
method.
HEADERS_RECEIVED
(numeric value 2)
All HTTP headers have been received. Several response members of the object are now available.
For non same origin requests the object will never be in this state.
LOADING
(numeric value 3)
The response entity body is being received.
DONE
(numeric
value 4)
The data transfer has been completed or something went wrong during the transfer (such as infinite redirects).
The OPENED state has an associated send()
flag that indicates whether the send()
method has been invoked. It can be either
"true" or "false" and has an initial value of "false".
The DONE state has an associated error flag that indicates some type of network error or abortion. It can be either "true" or "false" and has an initial value of "false".
This section defines the various members of the XMLHttpRequest
object that can
be used to initialize a network request.
When the open(method,
url, async, user,
password)
method is invoked, the user agent must act as if it had run the following steps (unless
otherwise indicated):
Let stored method be the method argument.
If stored method does not match the Method token raise a SYNTAX_ERR
exception and terminate these steps.
If stored method case-insensitively matches
CONNECT
, DELETE
, GET
,
HEAD
, OPTIONS
, POST
,
PUT
, TRACE
, or TRACK
convert stored method to
uppercase.
If it does not match any of the above, it is passed through literally, including in the final request.
If stored method is one of CONNECT
,
TRACE
, or TRACK
the user agent should raise a SECURITY_ERR
exception and terminate
these steps.
Allowing these methods would pose a security risk. [HTTPVERBSEC]
Resolve stored
url with the Document
pointer being the associated document and UTF-8 being the
encoding of that document. If the resolve a URL algorithm returns an error raise a
SYNTAX_ERR
exception and terminate these steps.
Drop <fragment>
from
stored url.
If stored url contains an unsupported <scheme>
raise a
NOT_SUPPORTED_ERR
and terminate these steps.
If the "user:password"
format in the
userinfo
production defined in section 3.2.1 of RFC 3986 is
not supported for the relevant scheme and stored url contains
this format raise a SYNTAX_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.
The previous level of this specification raised a SECURITY_ERR
at this place in case of a
non same origin stored url. This specification supports non
same origin requests and therefore this exception is no longer raised
here.
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.
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.
If the password argument was not omitted and is
null
remove stored password.
Abort the
send()
algorithm, set response entity body to "null" and
empty the author request headers
list.
This step and the next only has effect if send()
and/or setRequestHeader()
has been used.
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 a
readystatechange
event on the object and return the
method call.
The object has an associated list of author request headers consisting of HTTP
header name/value pairs. The setRequestHeader(header)
method can be used to set new request headers and append to request
headers already in the list.
As indicated in the algorithm below certain headers cannot be set and
are left up to the user agent. In addition there are certain other headers
the user agent will take control of if they are not set by the author as
indicated at the end of the send()
method
section.
The setRequestHeader()
method appends a
value if the header given as argument is already part of the author request headers list.
For non same origin requests using the HTTP GET
method a preflight request is made when headers other than
Accept
and Accept-Language
are set.
When setRequestHeader()
is
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 an INVALID_STATE_ERR
exception and terminate these
steps.
If the header argument does not match the field-name
production raise a
SYNTAX_ERR
exception and terminate these steps.
If the value argument does not match the field-value
production raise a
SYNTAX_ERR
and terminate these steps.
The empty string is legal and represents the empty header value.
For security reasons, these steps should be terminated if the header argument case-insensitively matches one of the following headers:
Accept-Charset
Accept-Encoding
Access-Control-Request-Headers
Access-Control-Request-Method
Authorization
Connection
Content-Length
Cookie
Cookie2
Content-Transfer-Encoding
Date
Expect
Host
Keep-Alive
Origin
Referer
TE
Trailer
Transfer-Encoding
Upgrade
User-Agent
Via
… or if the start of the header argument case-insensitively matches
Proxy-
or Sec-
(including when the argument is
just Proxy-
or Sec-
).
The above headers are not allowed to be set as they are
better controlled by the user agent as it knows best what value they
should have. Header names starting with Sec-
are not
allowed to be set to allow new headers to be minted in the future that
are guaranteed not to come from XMLHttpRequest
. (Older
clients would however still be vulnerable as they allow such headers to
be set.)
If the header argument is not in the author request headers list append the header with its associated value to the list and terminate these steps.
If the header argument is in the author request headers list 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
...
The credentials flag takes the values true and
false, true by default, and indicates whether a non same origin request includes cookie and HTTP
authentication data. It is used during the send()
algorithm.
When the withCredentials
attribute is set, the following
algorithm must be followed:
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 an INVALID_STATE_ERR
exception and terminate these
steps.
If the given value is true
, set the credentials flag to true. Otherwise, set the credentials flag to false.
On getting, the withCredentials
attribute must return true
if the credentials flag is true, and false
if the credentials flag is false.
To track the progress of data being uploaded through the send()
method the XMLHttpRequest
object offers an upload
attribute. On getting, this attribute
must return an object implementing the XMLHttpRequestUpload
interface. This object can be used to register event listeners on which
will be triggered during the upload process.
The current request URL is initially stored
url (as set by the open()
method)
and is updated as described in the send()
algorithm.
The upload complete flag indicates is used in several algorithms to determine whether or not to dispatch an event. The flag is either true or false (default).
The upload events flag is used in the
send()
algorithm to determine whether
upload progress events will be dispatched for non same origin requests.
The flag is either true or false (default).
When the steps for the send()
method
say something is a network error the user agent must act as if the following steps had been run:
Set the response entity body to "null", the error flag to "true" and empty the author request headers list.
Synchronously switch the state to DONE.
If async is set to false
raise a NETWORK_ERR
exception and terminate the
overall algorithm.
Synchronously dispatch a
readystatechange
event on the object.
Synchronously dispatch a progress
event called error
on the
object.
If the upload complete flag is
false, set the flag to true and synchronously dispatch a progress event called
error
on the object returned by
the upload
attribute.
Terminate the overall algorithm.
When the steps for the send()
method
say something is an abort error the user agent must act as if the following steps had been run:
Set the response entity body to "null", the error flag to "true" and empty the author request headers list.
Synchronously switch the state to DONE.
If async is set to false
raise an ABORT_ERR
exception and terminate the
overall algorithm.
Synchronously dispatch a
readystatechange
event on the object.
Synchronously dispatch a progress
event called abort
on the object.
If the upload complete flag is
false, set the flag to true and synchronously dispatch a progress event called
abort
on the
object returned by the upload
attribute.
Terminate the overall algorithm.
When the steps for the send()
method
say to switch to the HEADERS_RECEIVED
state the user agent must act as if the following
steps had been run:
Synchronously switch the state to HEADERS_RECEIVED.
Synchronously dispatch a
readystatechange
event on the object.
When the steps for the send()
method
say to switch to the LOADING state the user
agent must act as if the following steps had been run:
Synchronously switch the state to LOADING.
Synchronously dispatch a
readystatechange
event on the object.
When the steps for the send()
method
say to make progress notifications user agents must, while the download is progressing and async
is true
, dispatch a
progress event called progress
at the object every 350ms
(±200ms) or for every byte received, whichever is least
frequent.
When the steps for the send()
method
say to make upload progress notifications user agents
must, if async is true
, follow
these rules:
While the request entity body is being uploaded and the upload complete flag is false, dispatch a progress event called
progress
at the object
returned by the upload
attribute
every 350ms (±200ms) or for every byte transmitted, whichever is
least frequent.
If the request entity body has been successfully uploaded and the upload complete flag is still false,
set the flag to true and synchronously dispatch a progress event called
load
at the object returned by
the upload
attribute.
The send(data)
method initiates the request and its optional argument provides the entity body for the request. Authors are
encouraged to ensure that they have specified the
Content-Type
header via setRequestHeader()
before invoking
send()
with a non-null
data
argument.
When invoked, the user agent must act as if it had run
the following steps (unless otherwise noted). Note that this algorithm
might get aborted if the open()
or
abort()
method is invoked. When the send()
algorithm
is aborted the user agent must terminate the
algorithm after finishing the step it is on.
The send()
algorithm can only be
aborted when async is true
(i.e., the request is
done asynchronously) 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 an INVALID_STATE_ERR
exception and terminate these
steps.
If async is true
set the send()
flag to "true".
If async is true
and one or more event
listeners are registered on the object returned by the upload
attribute set the upload events flag to true. Otherwise,
set the upload events flag to false.
Synchronously dispatch a
readystatechange
event on the object.
The state of the object does not change. The event is dispatched for historical reasons.
If stored method is GET
or HEAD
act as if the data argument is null
.
If the data argument has not been omitted and is not
null
use it for the entity body
observing the following rules:
ByteArray
Use data literally for transmission.
DOMString
Encode data using UTF-8 for transmission.
Document
Let data be data.innerHTML
as
defined by section 2.5 of HTML 5. Encode it using
data.inputEncoding
or UTF-8 if
data.inputEncoding
is null
.
Re-raise any exceptions the data.innerHTML
getter algorithm raises. [HTML5]
If the document cannot be serialized the
document.innerHTML
algorithm raises an
INVALID_STATE_ERR
exception.
If no Content-Type
header has been set using setRequestHeader()
set a
Content-Type
request header with a value of
application/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.
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 data
is null
.
If the data argument has been omitted, or is
null
, no entity body is used in the request.
Set the upload complete flag to true if there is no request entity body or if the request entity is empty. Otherwise, set the upload complete flag to false.
If async is true
synchronously dispatch a progress event called
loadstart
on the object.
If async is true
and the request entity body
is not empty dispatch a progress
event called loadstart
on the object returned by the upload
attribute.
If async is true
return the send()
method call. (Do not terminate the steps
in the algorithm though.)
If the current request URL and the value of the
baseURI
attribute of the Document
pointer are same origin this is a same
origin request. Make a request to the current
request URL using HTTP method stored method, user
stored user (if provided), 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. Make progress notifications, make upload progress notifications, and follow the
list of request rules:
If the redirect violates security or infinite loop precautions or the scheme is not supported this is a network error.
Otherwise, run the following set of steps:
Set the current request URL to the new location.
If the current request URL and the value of
the baseURI
attribute of the Document
pointer are same origin follow the redirect while
observing the request rules for same origin requests.
Otherwise, follow the steps for a non same origin request terminating this one.
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.
This is an abort error.
In case of DNS errors, TLS negotiation failure, or other type of network errors, this is a network error. Do not request any kind of user interaction.
This does not include HTTP responses that indicate some type of error, such as HTTP status code 410.
Switch to the LOADING state and once the complete resource has been downloaded go to the next step.
Otherwise, if it is non same origin this is a non same origin request. Make a cross-site access request, passing these as parameters:
Document
pointer.
Handle the return values as described below.
The stored user and stored password variables are always ignored as part of a non same origin request as including them would allow a site to perform a distributed password search. However, user agents will include credentials in the request (if the user has any) as required elsewhere.
Also, make upload progress notifications, though only if a preflight request was made.
Set the current request URL to the value of the url return flag and then make a same origin request.
This is a network error.
This is an abort error.
Switch to the HEADERS_RECEIVED state, make progress notifications, and switch to the LOADING state once the first byte (or more) of the response entity body has been received or if there is no response entity body. Once the resource has been received completely go to the next step.
When the request has successfully completed loading, run the following steps:
Synchronously switch the state to DONE.
Synchronously dispatch a
readystatechange
event on the object.
Synchronously dispatch a progress
event called load
on the
object.
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 send Proxy-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 handle 401
Unauthorized
requests appropriately. If authentication fails,
stored user and stored password are not provided,
and the request is same origin, user agents should prompt the users for credentials. If authentication
fails, and stored user and stored password are
provided, user agents must not prompt the user for
credentials. [RFC2617]
Users are not prompted if credentials are provided through
the open()
API so that authors can
implement their own user interface. They are also not prompted for
cross-site requests.
If the user agent supports HTTP State Management it should persist, discard and send cookies (as received in the
Set-Cookie
and Set-Cookie2
response headers, and
sent in the Cookie
header) as applicable. [RFC2965]
If the user agent implements a HTTP cache it should
respect Cache-Control
request headers set by the setRequestHeader()
(e.g.,
Cache-Control: no-cache
bypasses the cache). It must not send Cache-Control
or
Pragma
request headers automatically unless the user
explicitly requests such behavior (e.g., by (force-)reloading
the page).
For 304 Not Modified
responses that are a result of a user
agent generated conditional request the user agent must
act as if the server gave a 200 OK
response with the
appropriate content. The user agent must allow setRequestHeader()
to override
automatic cache validation by setting request headers (e.g.,
If-None-Match
, If-Modified-Since
), in which case
304 Not Modified
responses must be passed
through. [RFC2616]
If the user agent implements server-driven content-negotiation it should set Accept-Encoding
and
Accept-Charset
headers as appropriate. Unless set through
setRequestHeader()
user
agents should set the Accept
and
Accept-Language
headers as well. If Accept
is
set by the user agent it must have the value
*/*
. Responses must have the
content-encodings automatically decoded. [RFC2616]
Besides the author request headers
user agents should not include additional request
headers other than those mentioned above or other than those authors are
not allowed to set using setRequestHeader()
. This ensures that
authors have a reasonably predictable API.
When the abort()
method is invoked, the
user agent must act as if it had 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 a
readystatechange
event on the object.
Switch the state to UNSENT. (Do not dispatch a readystatechange
event.)
Synchronously dispatch a progress
event called abort
on the object.
If the upload complete flag is
false, set the flag to true and synchronously dispatch a progress event called
abort
on the
object returned by the upload
attribute.
The getAllResponseHeaders()
method
provides access to all response headers as a single string. When invoked,
the user agent must act as if it had 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 sting 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 == 2) {
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
The Access Control for Cross-Site Requests specification
filters the headers that are exposed by getAllResponseHeaders()
.
[AC]
The getResponseHeader(header)
method returns the value of a response header given by the
header argument. When invoked, the user agent must act as if it had 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 return
null
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 COMMA followed by an U+0020 SPACE 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 Access Control for Cross-Site Requests specification
filters the headers that are exposed by getResponseHeader()
. [AC]
// The following script:
var client = new XMLHttpRequest();
client.open("GET", "test.txt", true);
client.send();
client.onreadystatechange = function() {
if(this.readyState == 2) {
print(client.getResponseHeader("Content-Type"));
}
}
// ...should output something similar to the following text:
Content-Type: text/plain; charset=utf-8
The status
attribute, on getting and
if available, must return the HTTP status code sent by
the server (typically 200
for a successful request). If not
available, the user agent must raise an
INVALID_STATE_ERR
exception.
The statusText
attribute, on
getting and if available, must return the HTTP status
text sent by the server (appears after the status code). If not available
(request is not initiated for instance), the user agent must raise an INVALID_STATE_ERR
exception.
The following subsection defines various variables and algorithms
important to the response body. The subsection after that defines the
members of the XMLHttpRequest
object relevant
to the response body.
The response MIME type is the MIME type
the Content-Type
header contains without any parameters or
"null" if the header could not be parsed properly or was omitted. The override MIME type is initially "null" and can
get a value if overrideMimeType()
is invoked. Final MIME type is the override MIME type unless
that is "null" in which case it is the response MIME type.
The response charset is the value of the
charset
parameter of the Content-Type
header or
null
if there was no charset
parameter or if the
header could not be parsed properly or was omitted. The override charset is initially "null" and can get
a value if overrideMimeType()
is invoked. Final charset is the override charset unless that
is "null" in which case it is the response charset.
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 the final charset.
Let mime be the final MIME type.
If charset is "null" and mime is "null",
text/xml
, application/xml
or ends in +xml
use the rules set forth in the XML specifications
to determine the character encoding. Let charset be the
determined character encoding.
If charset is "null" and mime is
text/html
follow the rules set forth in the HTML
specification to determine the character encoding. Let
charset be the determined character encoding. [HTML5]
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 |
---|---|
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 encode their resources using UTF-8.
The document response entity
body is either a Document
representing the response entity body or
null
. The document 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 final MIME type is not "null",
text/html
, text/xml
,
application/xml
, and does not end in +xml
terminate these steps and return null
.
If final MIME type is
text/html
let document be an object implementing
the Document
interface that represents the response entity body parsed following
the rules set forth in the HTML specification for an HTML parser with
scripting disabled and then terminate this algorithm. [HTML5]
Otherwise, let document be an object implementing the
Document
interface that represents the result of parsing
the response entity body into a document tree following the rules from
the XML specifications. 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.
Ensure that the cookie
attribute on document
returns the empty string if the same origin flag is
"false".
Return document.
When the overrideMimeType(mime)
method is invoked, the user agent must act as if it had
run the following steps:
If parsing mime analogously to the value of the
Content-Type
headers fails raise a SYNTAX_ERR
exception and abort this algorithm.
If a MIME type (without any parameters) is successfully parsed set override MIME type to that MIME type.
If a charset
parameter is successfully parsed set override charset to its value.
The responseBody
attribute, on
getting, must return the result of running the following
steps:
If the state is not LOADING or DONE
raise an INVALID_STATE_ERR
exception and terminate these
steps.
Return a ByteArray
object representing the response entity body or return
null
if the response entity body is "null".
The responseText
attribute, on
getting, must return the result of running 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.
The responseXML
attribute, on
getting, must return the result of running the following
steps:
If the state is not DONE
return null
and terminate these steps.
Return the document response entity body.
The responseXML
attribute has XML in its name for historical reasons. It also returns
documents created using an HTML parser.
The following events are dispatched on XMLHttpRequest
and/or XMLHttpRequestUpload
objects:
Event name | Interface | Dispatched when… |
---|---|---|
abort
| ProgressEvent
| When the request has been aborted. For instance, by invoking the
abort() method.
|
error
| ProgressEvent
| When the request has failed. |
load
| ProgressEvent
| When the request has successfully completed. |
loadstart
| ProgressEvent
| When the request starts. |
progress
| ProgressEvent
| While loading and sending data. |
readystatechange
| Event
| The readyState attribute
changes and at some seemingly arbitrary times for historical reasons.
|
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]
Thus, exceptions used by this specification and not defined in this section are defined by DOM Level 3 Core.
const unsigned short SECURITY_ERR = 18; const unsigned short NETWORK_ERR = 19; const unsigned short ABORT_ERR = 20;
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 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.
These exceptions might be folded into an update of DOM Level 3 Core in due course, as they are appropriate for other API specifications as well.
The editor would like to thank Alexey Proskuryakov, David Andersson, Elliotte Harold, Lachlan Hunt, Ian Hickson, Jonas Sicking, Maciej Stachowiak, Martin Hassman, Mohamed Zergaoui, Olli Pettay, and Rune Halvorsen for their contributions to this specification.
Thanks also to all who have contributed to The XMLHttpRequest
Object
specification.
Thanks also to all those who have helped to improve this specification by sending suggestions and corrections. (Please, keep bugging us with your issues!)