Copyright © 2009 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.
The XMLHttpRequest Level 2 specification enhances the XMLHttpRequest
object with new features, such as
cross-origin 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 20 August 2009 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 XMLHttpRequest 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
Interface
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 Cross-Origin Resource Sharing specification. [CORS]
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 also be a conforming implementation of the IDL fragments in this specification, as described in the Web IDL specification. [WebIDL]
A conforming user agent must be a conforming XML processor that reports violations of namespace well-formedness. [XML]
Comparing two strings in a case-sensitive manner means comparing them exactly, codepoint for codepoint.
Comparing two strings in an ASCII case-insensitive manner means comparing them exactly, codepoint for codepoint, except that the characters in the range U+0041 .. U+005A (i.e. LATIN CAPITAL LETTER A to LATIN CAPITAL LETTER Z) and the corresponding characters in the range U+0061 .. U+007A (i.e. LATIN SMALL LETTER A to LATIN SMALL LETTER Z) are considered to also match.
Converting a string to ASCII uppercase means replacing all characters in the range U+0061 .. U+007A (i.e. LATIN SMALL LETTER A to LATIN SMALL LETTER Z) with the corresponding characters in the range U+0041 .. U+005A (i.e. LATIN CAPITAL LETTER A to LATIN CAPITAL LETTER Z).
The terms and algorithms <fragment>, <scheme>, document base
URL, event handler
attributes, event handler event
type, fully active, Function
, innerHTML
, origin, resolve a URL, same origin, storage
mutex, task, task
source, URL, URL
character encoding, and queue a task 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]
userinfo
is used as described in
section 3.2.1 of RFC 3986. [RFC3986]
The terms cross-origin request and cross-origin request status are defined by the Cross-Origin Resource Sharing specification. [CORS]
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, is to be dispatched at the XMLHttpRequest
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-webapps@w3.org.
XMLHttpRequest
InterfaceThe XMLHttpRequest
object can
be used by scripts to programmatically connect to servers via HTTP.
[NoInterfaceObject] interface XMLHttpRequestEventTarget : EventTarget { // event handler attributes attribute Function onloadstart; attribute Function onprogress; attribute Function onabort; attribute Function onerror; attribute Function onload; attribute Function onloadend; }; interface XMLHttpRequestUpload : XMLHttpRequestEventTarget { // for future use }; [Constructor] interface XMLHttpRequest : XMLHttpRequestEventTarget { // event handler attributes attribute Function onreadystatechange; // 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 void open(DOMString method, DOMString url); void open(DOMString method, DOMString url, boolean async); void open(DOMString method, DOMString url, boolean async, DOMString? user); void open(DOMString method, DOMString url, boolean async, DOMString? user, DOMString? password); void setRequestHeader(DOMString header, DOMString value); attribute boolean withCredentials; readonly attribute XMLHttpRequestUpload upload; void send(); void send(ByteArray data); void send(Document data); void send([AllowAny] DOMString? data); void abort(); // response readonly attribute unsigned short status; readonly attribute DOMString statusText; DOMString getResponseHeader(DOMString header); DOMString getAllResponseHeaders(); void overrideMimeType(DOMString mime); readonly attribute ByteArray responseBody; readonly attribute DOMString responseText; readonly attribute Document responseXML; };
Each XMLHttpRequest
object
has an associated XMLHttpRequest
origin and an
XMLHttpRequest
base
URL.
This specification defines their values when the global object is
represented by the Window
object. When the XMLHttpRequest
object used in other
contexts their values will have to be defined as appropriate for that
context. That is considered to be out of scope for this specification.
In environments where the global object is represented by the
Window
object the XMLHttpRequest
object has an associated
XMLHttpRequest
Document
which is the Document
object
associated with the Window
object for which the XMLHttpRequest
interface object was
created.
The XMLHttpRequest
Document
is used to determine the XMLHttpRequest
origin and
XMLHttpRequest
base
URL at a later stage.
The following task sources are used by this specification:
XMLHttpRequest
event
task source
XMLHttpRequest
networking task source
Unless otherwise stated the task source used
for all tasks queued in
this specification is the XMLHttpRequest
event
task source.
When the XMLHttpRequest()
constructor is
invoked, the user agent must return a new XMLHttpRequest
object.
The following are the event
handler attributes (and their corresponding event
handler event types) that must be supported on
objects implementing an interface that inherits from XMLHttpRequestEventTarget
as
DOM attributes:
event handler attribute | event handler event type |
---|---|
onloadstart
| loadstart
|
onprogress
| progress
|
onabort
| abort
|
onerror
| error
|
onload
| load
|
onloadend
| loadend
|
The following is the event handler attribute (and its corresponding event handler event type) that must be supported as DOM attribute solely by the XMLHttpRequest
object:
event handler attribute | event handler event type |
---|---|
onreadystatechange
| readystatechange
|
The XMLHttpRequest
object can
be in several states. The readyState
attribute, on getting, must return the current state,
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.
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 (e.g. 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.
The XMLHttpRequest
object
holds the following request metadata variables:
The XMLHttpRequest
object
also has an associated XMLHttpRequestUpload
object.
open()
methodWhen the open(method,
url, async, user,
password)
method is invoked, the user agent must run these steps (unless otherwise indicated):
If the XMLHttpRequest
object has an associated XMLHttpRequest
Document
run these substeps:
If the XMLHttpRequest
Document
is not fully
active raise an INVALID_STATE_ERR
exception and
terminate the overall set of steps.
Let XMLHttpRequest
base URL be the document base URL
of the XMLHttpRequest
Document
.
Let XMLHttpRequest
origin be the origin of the XMLHttpRequest
Document
.
If method does not match the Method
token production raise a SYNTAX_ERR
exception and
terminate these steps.
If method is an ASCII
case-insensitive match for CONNECT
,
DELETE
, GET
, HEAD
,
OPTIONS
, POST
, PUT
,
TRACE
, or TRACK
convert method to ASCII uppercase.
If it does not match any of the above, it is passed through literally, including in the final request.
If method is a case-sensitive
match for CONNECT
, TRACE
, or
TRACK
the user agent should raise a
SECURITY_ERR
exception and
terminate these steps.
Allowing these methods poses a security risk. [HTTPVERBSEC]
Let url be a URL.
Let URL character encoding of url be UTF-8.
Resolve url relative to the XMLHttpRequest
base
URL. If the algorithm returns an error raise a
SYNTAX_ERR
exception and terminate these steps.
Drop <fragment>
from url.
If url contains an unsupported <scheme>
raise a
NOT_SUPPORTED_ERR
and terminate these steps.
If the "user:password"
format in the userinfo
production is not supported for the
relevant scheme and url contains this format raise a
SYNTAX_ERR
and terminate these steps.
If url contains the "user:password"
format let temp user be the user part and temp
password be the password part.
If url just contains the "user"
format let temp 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.
Let async be the value of the async argument or
true
if it was omitted.
If the user argument was not omitted follow these sub steps:
If the syntax of user does not match the syntax specified
by the relevant authentication scheme, raise a SYNTAX_ERR
exception and terminate the overall set of steps.
If user is null
let temp user be
null.
Otherwise let temp user be user.
These steps override anything that may have been set by the url argument.
If the password argument was not omitted follow these sub steps:
If the syntax of password does not match the syntax
specified by the relevant authentication scheme, raise a
SYNTAX_ERR
exception and terminate the overall set of
steps.
If password is null
let temp
password be null.
Otherwise let temp password be password.
These steps override anything that may have been set by the url argument.
The user agent should cancel any network activity for which the object is responsible.
Set variables associated with the object as follows:
Set the send()
flag to false.
Set response entity body to null.
Empty the list of author request headers.
Set the request method to method.
Set the request URL to url.
Set the request username to temp user.
Set the request password to temp password.
Set the asynchronous flag to true
if async is true
. Otherwise set it to false.
Switch the the state to OPENED.
setRequestHeader()
methodAs 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 HTTP 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 the setRequestHeader(header,
value)
method is invoked, the user agent must run these steps (unless otherwise indicated):
If the state 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 header 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 header is an ASCII case-insensitive match for one of the following headers:
Accept-Charset
Accept-Encoding
Access-Control-Request-Headers
Access-Control-Request-Method
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 header is an ASCII case-insensitive match for
Proxy-
or Sec-
(including when
header 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 header is not in the author request headers list append header with its associated value to the list and terminate these steps.
If header 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
...
withCredentials
attributeThe withCredentials
attribute
controls the credentials flag.
When the withCredentials
attribute is set, the user agent must run these steps:
If the state 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.
upload
attributeThe upload
attribute, on getting, must return the associated XMLHttpRequestUpload
object.
send()
methodThe 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 run these steps
(unless otherwise noted). 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 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 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
This will be done in terms of the File API in due course.
Use data literally for transmission.
DOMString
Encode data using UTF-8 for transmission.
Document
Let tempdata be the result of getting the innerHTML
attribute on the data object and encode it using
data.inputEncoding
or UTF-8 if
data.inputEncoding
is null
.
Re-raise any exception this raises.
If the document cannot be serialized an
INVALID_STATE_ERR
exception is raised.
Let data be tempdata.
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.
If the data argument has been omitted, or is
null
, no entity body is used in the request.
If the asynchronous flag is false release the storage mutex.
If the asynchronous flag is true and
one or more event listeners are registered on the XMLHttpRequestUpload
object set
the upload events flag to true.
Otherwise, set the upload events flag
to false.
Set the error flag to false.
Set the upload complete flag to true if there is no request entity body or if the request entity body is empty. Otherwise, set the upload complete flag to false.
If the asynchronous flag is true run these substeps:
Set the send()
flag to true.
Dispatch a
readystatechange
event.
The state does not change. The event is dispatched for historical reasons.
Dispatch a progress event
called loadstart
.
If the upload complete flag is
false dispatch a progress event
called loadstart
on the
XMLHttpRequestUpload
object.
Return the send()
method call, but
continue running the steps in this algorithm.
XMLHttpRequest
origin and the request URL are same origin
These are the same-origin request steps.
Make a request to request URL, using HTTP method request method, user request username (if non-null) and password request password (if non-null), taking into account the request entity body, list of author request headers and the rules listed at the end of this section.
If there are cookies to be set, run the cookie steps.
While making the request also follow the same-origin request event rules.
The send()
method call
will now be returned by virtue of this algorithm ending.
Make upload progress notifications.
While processing the request, as data becomes available and when
the user interferes with the request, queue tasks to follow the same-origin request event
rules using the XMLHttpRequest
networking task source as task
source.
These are the cross-origin request steps.
Make a cross-origin request, passing these as parameters:
XMLHttpRequest
origin.
Request username and request password are always ignored as part of a cross-origin request; 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.
If there are cookies to be set and the credentials flag is true, run the cookie steps.
While making the request also follow the cross-origin request event rules.
The send()
method call
will now be returned by virtue of this algorithm ending.
While processing the request, as data becomes available and when
the end user interferes with the request, queue tasks to follow the cross-origin request event
rules using the XMLHttpRequest
networking task source as task
source.
If the user agent allows the end 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 and
Authorization
is not in the list of author request headers, it should consider requests originating from the XMLHttpRequest
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, and
request username and request
password are both null, user agents should prompt
the end user for credentials. If authentication fails, and request username and request password are provided, user agents
must not prompt the end user for credentials. [RFC2617]
End 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. [COOKIES]
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 end 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.
send()
methodThe cookie steps are as follows:
Wait until ownership of the storage mutex can be taken.
Take ownership of the storage mutex.
Update the cookies. [COOKIES]
Release the storage mutex so that it is once again free.
The same-origin request event rules are as follows:
If the redirect violates security or infinite loop precautions or the scheme is not supported this is a network error.
Otherwise, run these steps:
Set the request URL to the URL conveyed by the Location
header.
If the XMLHttpRequest
origin and request URL are same origin follow the redirect while
observing the same-origin
request event rules.
Otherwise, follow the cross-origin request steps and terminate the steps for this algorithm.
HTTP places requirements on the user agent regarding the preservation of the request method and request entity body during redirects, and also requires end 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 end user interaction.
This does not include HTTP responses that indicate some type of error, such as HTTP status code 410.
The cross-origin request event rules are as follows:
This is a network error.
This is an abort error.
When something is said to be a network error run these steps:
Set the response entity body to null.
Set the the error flag to true.
Empty the list of author request headers.
Switch the state to DONE.
If the asynchronous flag is false
raise a NETWORK_ERR
exception
and terminate the overall set of steps.
Queue a task to dispatch a
readystatechange
event.
At this point it is clear that the asynchronous flag is true.
Queue a task to dispatch a progress event called
error
.
Queue a task to dispatch a progress event called
loadend
.
If the upload complete flag is false, follow these substeps:
Set the upload complete flag to true.
Queue a task to dispatch a progress event called
error
on the XMLHttpRequestUpload
object.
Queue a task to dispatch a progress event called
loadend
on the XMLHttpRequestUpload
object.
Terminate the overall algorithm.
When something is said to be an abort error run these steps:
Set the response entity body to null.
Set the the error flag to true.
Empty the list of author request headers.
Switch the state to DONE.
If the asynchronous flag is false
raise a ABORT_ERR
exception and
terminate the overall set of steps.
Queue a task to dispatch a
readystatechange
event.
At this point it is clear that the asynchronous flag is true.
Queue a task to dispatch a progress event called
abort
.
Queue a task to dispatch a progress event called
loadend
.
If the upload complete flag is false, follow these substeps:
Set the upload complete flag to true.
Queue a task to dispatch a progress event called
abort
on the
XMLHttpRequestUpload
object.
Queue a task to dispatch a progress event called
loadend
on the XMLHttpRequestUpload
object.
Terminate the overall algorithm.
When it is said to switch to the HEADERS_RECEIVED state run these steps:
Switch the state to HEADERS_RECEIVED.
When it is said to switch to the LOADING state run these steps:
Switch the state to LOADING.
When it is said to switch to the DONE state run these steps:
Switch the state to DONE.
If the asynchronous flag is false run these substeps:
If the asynchronous flag is true run these substeps:
Queue a task to dispatch a progress event called
load
.
Queue a task to dispatch a progress event called
loadend
.
When it is said to make progress
notifications, while the download is progressing, queue a task to dispatch a progress event called
progress
about every 50ms or
for every byte received, whichever is least frequent.
When it is said to make upload progress notifications run these steps:
While the request entity body is being uploaded and the upload complete flag is false, queue a task to dispatch a progress event called
progress
at the XMLHttpRequestUpload
object
about every 50ms 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, run these substeps:
Set the upload complete flag to true.
Queue a task to dispatch a progress event called
load
at the XMLHttpRequestUpload
object.
Queue a task to dispatch a progress event called
loadend
at the XMLHttpRequestUpload
object.
abort()
methodWhen the abort()
method is invoked, the
user agent must run these steps (unless otherwise
noted):
The user agent should cancel any network activity for which the object is responsible.
Set the response entity body to null.
Set the error flag to true.
Empty the list of author request headers.
If the state is UNSENT, OPENED with the send()
flag being false, or DONE go to the next step.
Otherwise run these substeps:
Switch the state to DONE.
Set the send()
flag to false.
Dispatch a progress event
called abort
.
Dispatch a progress event
called loadend
.
If the upload complete flag is false run these substeps:
Set the upload complete flag to true.
Dispatch a progress event
called abort
on the XMLHttpRequestUpload
object.
Dispatch a progress event
called loadend
on the
XMLHttpRequestUpload
object.
Switch the state to UNSENT.
No readystatechange
event is
dispatched.
status
attributeThe status
attribute must return the result of running these 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
0
and terminate these steps.
Return the HTTP status code.
statusText
attributeThe statusText
attribute must return the result of running these 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 the HTTP status text.
getResponseHeader()
methodWhen the getResponseHeader(header)
is invoked, the user agent must run these steps:
If the state is UNSENT or OPENED raise an INVALID_STATE_ERR
exception and
terminate these steps.
If header 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 header is an ASCII
case-insensitive match for Set-Cookie
or
Set-Cookie2
return null
and terminate these
steps.
If header is an ASCII case-insensitive match for multiple HTTP response headers, return the values of these headers as a single concatenated string separated from each other by a U+002C COMMA U+0020 SPACE character pair and terminate these steps.
If header is an ASCII case-insensitive match for a single HTTP response header, return the value of that header and terminate these steps.
Return null
.
The Cross-Origin Resource Sharing specification filters the
headers that are exposed by getResponseHeader()
for non
same-origin requests. [CORS]
// 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
getAllResponseHeaders()
methodWhen the getAllResponseHeaders()
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 error flag is true return the empty string and terminate these steps.
Return all the HTTP headers, excluding headers that are an ASCII case-insensitive match for
Set-Cookie
or Set-Cookie2
, as a single string,
with each header line separated by a U+000D CR U+000A LF pair excluding
the status line, and with each header name and header value separated by
a U+003A COLON U+0020 SPACE pair.
// 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 Cross-Origin Resource Sharing specification filters the
headers that are exposed by getAllResponseHeaders()
for non
same-origin requests. [CORS]
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]
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.
overrideMimeType()
methodWhen the overrideMimeType(mime)
method is invoked, the user agent must 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.
responseBody
attributeThis will be done in terms of the File API in due course.
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.
responseText
attributeThe 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.
responseXML
attributeThe 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… |
---|---|---|
readystatechange
| Event
| The readyState attribute
changes at some seemingly arbitrary times for historical reasons.
|
loadstart
| ProgressEvent
| When the request starts. |
progress
| ProgressEvent
| While loading and sending data. |
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. |
loadend
| ProgressEvent
| When the request has completed (either in success or failure). |
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.
XMLHttpRequest Level 2 adds the following new features:
The ability to make cross-origin requests.
The ability to register for progress events. Both for downloads (put
listeners on the XMLHttpRequest
object itself) and
uploads (put listeners on the XMLHttpRequestUpload
object,
returned by the upload
attribute).
The ability to override the media type and character encoding of the
response through the overrideMimeType()
method.
byte streams
Unless marked "Non-normative" these references are normative.
The editor would like to thank Alexey Proskuryakov, Cameron McCormack, David Andersson, David Levin, 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
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!)