To the extent possible under law, the editor has waived all copyright and
related or neighboring rights to this work. In addition, as of
23 November 2011, the editor has made this specification available
under the
Open Web Foundation Agreement Version 1.0,
which is available at
http://www.openwebfoundation.org/legal/the-owf-1-0-agreements/owfa-1-0.
The XMLHttpRequest specification defines an API that provides scripted client functionality for transferring data between a client and a server.
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 23 November 2011 Editor's Draft of XMLHttpRequest. Please send comments to public-webapps@w3.org (archived) with [XHR] at the start of the subject line.
For the last Last Call Working Draft the Working Group has kept a disposition of comments document. A list of changes is available via a Web view of CVS. (Due to the way the document is edited certain commit messages have introduced negligible changes to this document and are in fact only relevant for XMLHttpRequest Level 2.)
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.
To exit the Candidate Recommendation (CR) stage the following criteria must have been met:
XMLHttpRequest
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. It is the ECMAScript HTTP API.
[ECMASCRIPT]
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 processData(data) {
// taking care of data
}
function handler() {
if(this.readyState == this.DONE) {
if(this.status == 200 &&
this.responseXML != null &&
this.responseXML.getElementById('test').textContent) {
// success!
processData(this.responseXML.getElementById('test').textContent);
return;
}
// something went wrong
processData(null);
}
}
var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("GET", "unicorn.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 == this.DONE)
returnStatus(this.status);
}
client.open("HEAD", address);
client.send();
}
Everything in this specification is normative except for diagrams, examples, notes and sections marked non-normative.
The key words must, must not, should, should not 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 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.
This specification relies on several underlying specifications.
A conforming user agent must
support at least the subset of the functionality defined in DOM4 that
this specification relies upon, such as various exceptions and
EventTarget. [DOM]
A conforming user agent must
support at least the subset of the functionality defined in File API that
this specification relies upon, such as the Blob and
File interfaces. [FILEAPI]
A conforming user agent must
support at least the subset of the functionality defined in HTML that
this specification relies upon, such as the basics of the
Window object and serializing a Document
object. [HTML]
A conforming user agent must support some version of the HTTP protocol. Requirements regarding HTTP are made throughout the specification. [HTTP]
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] [XMLNS]
User agents, Working Groups, and other interested parties are
strongly encouraged to discuss extensions on a relevant public
forum, preferably
public-webapps@w3.org. If this
is for some reason not possible prefix the extension in some way and start
the prefix with an uppercase letter. E.g. if company Foo wants to add a
private method bar() it could be named FooBar()
to prevent clashes with a potential future standardized
bar().
To deflate a DOMString into a byte sequence means to create a sequence of bytes such that the nth byte of the sequence is equal to the low-order byte of the nth code point in the original DOMString.
To inflate a byte sequence into a DOMString means to create a DOMString such that the nth code point has 0x00 as the high-order byte and the nth byte of the byte sequence as the low-order byte.
XMLHttpRequestThe XMLHttpRequest object can be used by scripts to issue
HTTP requests.
[NoInterfaceObject]
interface XMLHttpRequestEventTarget : EventTarget {
// for future use
};
[Constructor]
interface XMLHttpRequest : XMLHttpRequestEventTarget {
// event handler
[TreatNonCallableAsNull] 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, optional boolean async, optional DOMString? user, optional DOMString? password);
void setRequestHeader(DOMString header, DOMString value);
void send();
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();
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 is 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
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.
Each XMLHttpRequest object has its own
task source. Namely, the
XMLHttpRequest task source.
XMLHttpRequest()XMLHttpRequest object.The XMLHttpRequest()
constructor must return a new XMLHttpRequest object.
An XMLHttpRequest object must not be garbage collected if
its state is OPENED and the
send() flag is set, its state is
HEADERS_RECEIVED, or
its state is LOADING, and
it has one or more
event listeners
registered whose type is
readystatechange.
If an XMLHttpRequest object is garbage collected while its
connection is still open, the user agent must cancel any instance of the
fetch algorithm opened by this object,
discarding any tasks
queued for them, and
discarding any further data received from the network for them.
The following is the
event handler
(and its corresponding
event handler event type) that must be
supported as attribute by the
XMLHttpRequest object:
| event handler | event handler event type |
|---|---|
onreadystatechange
| readystatechange |
readyStateReturns the current state.
The XMLHttpRequest object can be in several states. The
readyState
attribute 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 redirects (if any) have been followed and all HTTP headers of the final response 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 error flag indicates some type of network error or abortion. It is used during the DONE state. It can be either true or false and has an initial value of false.
The XMLHttpRequest object holds the following request
metadata variables:
open() methodopen(method,
url, async, user,
password)Sets the request method, request URL, synchronous flag, request username, and request password.
Throws a "SyntaxError" exception if
one of the following is true:
"user:password"
format in the userinfo production.
Throws a "SecurityError" exception
if method is a case-insensitive match for
CONNECT, TRACE or TRACK.
Throws an "InvalidAccessError"
exception if one of the following is true:
XMLHttpRequest origin.
XMLHttpRequest document and either the
timeout attribute is not
zero, the
withCredentials
attribute is true, or the
responseType
attribute is not the empty string.
The
open(method, url, async, user, password)
method must run these steps (unless otherwise indicated):
If there is an associated
XMLHttpRequest document run
these substeps:
If the
XMLHttpRequest document is not
fully active,
throw an
"InvalidStateError" 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 any code point in method is higher than
U+00FF LATIN SMALL LETTER Y WITH DIAERESIS or after
deflating
method it does not match the
Method token production,
throw a
"SyntaxError" exception and terminate
these steps. Otherwise let method be the result of
deflating
method.
If method is a case-insensitive match for
CONNECT, DELETE, GET,
HEAD, OPTIONS, POST,
PUT, TRACE, or TRACK
subtract 0x20 from each byte in the range 0x61 (ASCII a) to
0x7A (ASCII z).
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,
throw a
"SecurityError" exception and
terminate these steps.
Allowing these methods poses a security risk. [HTTPVERBSEC]
Let url be a URL with character encoding UTF-8.
Resolve url
relative to the XMLHttpRequest base URL.
If the algorithm returns an error,
throw a
"SyntaxError" exception and terminate
these steps.
Drop
<fragment> from
url.
If the "user:password" format in the
userinfo production is not supported
for the relevant
<scheme> and
url contains this format,
throw a
"SyntaxError" 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.
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 user is not null and the
origin of url is not
same origin with the
XMLHttpRequest origin,
throw an
"InvalidAccessError" exception and
terminate the overall set of steps.
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 password is not null and the
origin of url is not
same origin with the
XMLHttpRequest origin,
throw an
"InvalidAccessError" exception and
terminate the overall set of steps.
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.
If there are any
tasks from the
object's XMLHttpRequest task source in one of
the task queues,
then remove them.
Set variables associated with the object as follows:
Set the request method to method.
Set the request URL to url.
If async is false, set the synchronous flag.
Set the request username to temp user.
Set the request password to temp password.
Empty the list of author request headers.
Set the send() flag to false.
Set response entity body to null.
Change the state to OPENED.
Fire an event named readystatechange.
setRequestHeader() methodsetRequestHeader(header, value)Appends an header to the list of author request headers, or if header is already in the list of author request headers, combines its value with value.
Throws an "InvalidStateError"
exception if the state is not
OPENED or if the
send() flag is true.
Throws a "SyntaxError" exception if
header is not a valid HTTP header field name or if
value is not a valid HTTP header field value.
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(header, value)
method must run these steps:
If the state is not
OPENED,
throw an
"InvalidStateError" exception and
terminate these steps.
If the send() flag is true,
throw an
"InvalidStateError" exception and
terminate these steps.
If any code point in header is higher than
U+00FF LATIN SMALL LETTER Y WITH DIAERESIS or after
deflating
header it does not match the
field-name production,
throw a
"SyntaxError" exception and terminate
these steps. Otherwise let header be the result of
deflating
header.
If any code point in value is higher than
U+00FF LATIN SMALL LETTER Y WITH DIAERESIS or after
deflating
value it does not match the
field-value production,
throw a
"SyntaxError" exception and terminate
these steps. Otherwise let value be the result of
deflating
value.
The empty string is legal and represents the empty header value.
Terminate these steps if header is a case-insensitive match for one of the following headers:
Accept-CharsetAccept-EncodingAccess-Control-Request-HeadersAccess-Control-Request-MethodConnectionContent-LengthCookieCookie2Content-Transfer-EncodingDateExpectHostKeep-AliveOriginRefererTETrailerTransfer-EncodingUpgradeUser-AgentVia… or if the start of header is a case-insensitive
match for Proxy- or Sec- (including when
header is just Proxy- or Sec-).
The above headers are controlled by the user agent to
let it control those aspects of transport. This guarantees data
integrity to some extent. Header names starting with Sec-
are not allowed to be set to allow new headers to be minted that are
guaranteed not to come from XMLHttpRequest.
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). [HTTP]
See also the
send() method regarding user
agent header handling for caching, authentication, proxies, and
cookies.
Some simple code demonstrating what happens when setting the same header twice:
// The following script:
var client = new XMLHttpRequest();
client.open('GET', 'demo.cgi');
client.setRequestHeader('X-Test', 'one');
client.setRequestHeader('X-Test', 'two');
client.send();
// …results in the following header being sent:
X-Test: one, two
send() methodsend(data)Initiates the request. The optional argument provides the
request entity body. The argument is ignored if
request method is GET or
HEAD.
Throws an "InvalidStateError"
exception if the state is not
OPENED or if the
send() flag is true.
The
send(data)
method must run these steps (unless otherwise noted). This algorithm can
be terminated by invoking the
open() or
abort() method. When it is
terminated the user agent
must terminate the algorithm after finishing the step it is on.
The send()
algorithm can only be terminated if the synchronous flag is
unset and only after the method call has returned.
If the state is not
OPENED,
throw an
"InvalidStateError" exception and
terminate these steps.
If the send() flag is true,
throw an
"InvalidStateError" exception and
terminate these steps.
If the request method is a case-sensitive match for
GET or HEAD act as if data
is null.
If the data argument has been omitted or is null, do not include a request entity body and go to the next step.
Otherwise, let encoding be null, mime type be null, and then follow these rules:
Document
Let encoding be the preferred MIME name of the character encoding of data. If encoding is UTF-16 change it to UTF-8.
Let mime type be "application/xml" or
"text/html" if
Document is an
HTML document, followed by
";charset=", followed by encoding.
Let the request entity body be the result of getting
the innerHTML
attribute on data
converted to Unicode
and encoded as encoding. Re-throw any exception this
throws.
In particular, if the document cannot be serialized an
"InvalidStateError" exception is
thrown.
Subsequent changes to the
Document have no effect on what
is transferred.
DOMStringLet encoding be UTF-8.
Let mime type be "text/plain;charset=UTF-8".
Let the request entity body be data converted to Unicode and encoded as UTF-8.
If a Content-Type header is in
author request headers and its value is a
valid MIME type that has a
charset parameter whose value is not a case-insensitive
match for encoding, and encoding
is not null, set all the charset parameters of that
Content-Type header to encoding.
If no Content-Type header is in
author request headers and mime type is
not null, append a Content-Type header with value
mime type to author request headers.
If the synchronous flag is set release the storage mutex.
Set the error flag to false.
If the synchronous flag is unset, run these substeps:
Set the send() flag to true.
Fire an event named readystatechange.
The state does not change. The event is dispatched for historical reasons.
Return the send()
method call, but continue running the steps in this algorithm.
XMLHttpRequest origin and the
request URL are same originThese are the same-origin request steps.
Fetch the
request URL from origin
XMLHttpRequest origin, with the
synchronous flag set if the
synchronous flag is set, 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.
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.
While processing the request, as data becomes available and when the user interferes with the request, queue tasks to update the response entity body and follow the same-origin request event rules.
These are the cross-origin request steps.
This is a network error.
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,
XMLHttpRequest origin and the
request URL are same origin,
Authorization is not in the list
of author request headers, request username is
null, and request password is null, user agents
should prompt the end user for their username and
password.
Otherwise, if authentication fails, user agents must not prompt the end user for their username and password. [HTTPAUTH]
End users are not prompted for various cases so that authors can implement their own user interface.
If the user agent supports HTTP State Management it
should persist, discard and send cookies (as received
in the Set-Cookie response header, and sent in the
Cookie header) as applicable.
[COOKIES]
If the user agent implements a HTTP cache it should
respect Cache-Control headers in
author request headers
(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 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 author request headers to override automatic cache
validation (e.g. If-None-Match or
If-Modified-Since), in which case
304 Not Modified responses must be passed through.
[HTTP]
If the user agent implements server-driven content-negotiation
it must follow these constraints for the
Accept and Accept-Language request headers:
Both headers must not be modified if they are in author request headers.
If not in author request headers,
Accept-Language with an appropriate value should be appended
to it.
If not in author request headers, Accept
with value */* must be appended to it.
Responses must have the content-encodings automatically decoded. [HTTP]
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 predictable API.
send() methodThe same-origin request event rules are as follows:
If the redirect violates infinite loop precautions 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 the
origin of request URL
are same origin transparently 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.
When something is said to be a network error run the
request error steps for exception
"NetworkError".
When something is said to be an abort error run the
request error steps for exception
"AbortError".
When something is said to be a request error for exception exception run these steps:
The user agent should cancel any network activity for which the object is responsible.
If there are any
tasks from the
object's XMLHttpRequest task source in one of
the task queues,
then remove them.
Set the the error flag to true.
Change the state to DONE.
If the synchronous flag is set, throw an exception exception and terminate the overall set of steps.
Fire an event named readystatechange.
At this point it is clear that the synchronous flag is unset.
A future version of this specification will dispatch an
error/abort
event here as well. (Depending on the type of error.)
When it is said to switch to the HEADERS_RECEIVED state run these steps:
Change the state to HEADERS_RECEIVED.
Fire an event named readystatechange.
When it is said to switch to the LOADING state run these steps:
Change the state to LOADING.
Fire an event named readystatechange.
When it is said to switch to the DONE state run these steps:
If the synchronous flag is set, update the response entity body.
Change the state to DONE.
Fire an event named readystatechange.
abort() methodabort()The
abort()
method must run these steps (unless otherwise noted). This algorithm can
be terminated by invoking the
open() method. When it is
terminated the user agent
must terminate the algorithm after finishing the step it is on.
The abort()
algorithm can only be terminated by invoking
open() from an event
handler.
The user agent should cancel any network activity for which the object is responsible.
If there are any
tasks from the
object's XMLHttpRequest task source in one of
the task queues,
then remove them.
Set the error flag to true.
If the state is UNSENT,
OPENED with the
send() flag being false, or
DONE go to the next step.
Otherwise run these substeps:
Change the state to DONE.
Set the send() flag to false.
Fire an event named readystatechange.
A future version of this specification will dispatch an
abort event here.
Change the state to UNSENT.
No readystatechange event is dispatched.
status attributestatusReturns the HTTP status code.
The
status
attribute must return the result of running these
steps:
If the state is UNSENT or OPENED return 0 and terminate these steps.
If the error flag is true return 0 and terminate these steps.
Return the HTTP status code.
statusText attributestatusTextReturns the HTTP status text.
The
statusText
attribute must return the result of running these
steps:
If the state is UNSENT or OPENED return the empty string and terminate these steps.
If the error flag is true return the empty string and terminate these steps.
Return the HTTP status text.
getResponseHeader() methodgetResponseHeader(header)Returns the header field value from the response of which the
field name matches header, unless the field name is
Set-Cookie or Set-Cookie2.
The
getResponseHeader(header)
method must run these steps:
If the state is UNSENT or OPENED return null and terminate these steps.
If the error flag is true return null and terminate these steps.
If any code point in header is higher than U+00FF LATIN SMALL LETTER Y WITH DIAERESIS return null and terminate these steps.
Let header be the result of deflating header.
If header is a case-insensitive match for
Set-Cookie or Set-Cookie2 return null and
terminate these steps.
If header is a case-insensitive match for multiple HTTP response headers, return the inflated 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 a case-insensitive match for a single HTTP response header, return the inflated value of that header and terminate these steps.
Return null.
For the following script:
var client = new XMLHttpRequest();
client.open("GET", "unicorns-are-teh-awesome.txt", true);
client.send();
client.onreadystatechange = function() {
if(this.readyState == 2) {
print(client.getResponseHeader("Content-Type"));
}
}
The print() function will get to process something
like:
text/plain; charset=UTF-8
getAllResponseHeaders() methodgetAllResponseHeaders()Returns all headers from the response, with the exception of those
whose field name is Set-Cookie or
Set-Cookie2.
The
getAllResponseHeaders()
method must run these steps:
If the state is UNSENT or OPENED return the empty string 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 a
case-insensitive match for Set-Cookie or
Set-Cookie2,
inflated,
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.
For the following script:
var client = new XMLHttpRequest();
client.open("GET", "narwhals-too.txt", true);
client.send();
client.onreadystatechange = function() {
if(this.readyState == 2) {
print(this.getAllResponseHeaders());
}
}
The print() function will get to process something
like:
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 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
always null. 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 always null.
Final charset is the override charset unless
that is null in which case it is the response charset.
Override MIME type and override charset are introduced here solely to make editing several levels of XMLHttpRequest simultaneously somewhat easier. Apologies for any confusion they might cause.
The response entity body is the fragment of the entity body of the response received so far (LOADING) or the complete entity body of the response (DONE). If the response does not have an entity body the response entity body is null.
The response entity body is updated as part
of the send() algorithm.
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.
[HTML]
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 REPLACEMENT CHARACTER character. Remove one leading U+FEFF BYTE ORDER MARK character, if present.
Authors are strongly encouraged to always encode their resources using UTF-8.
The document response entity
body is either a Document representing the
response entity body or null. If it is a
Document its origin is the
XMLHttpRequest origin. If the
document response entity body has no value assigned to it let
it be the return value of the following algorithm:
If the response entity body is null, return null and terminate these steps.
If final MIME type is not null,
text/xml,
application/xml, or does not end in
+xml, return null and terminate these
steps.
Let document be a
Document object that represents the result of parsing the
response entity body into a document tree following the
rules set forth in the XML specifications. If that fails
(unsupported character encoding, namespace well-formedness error et
cetera) return null and terminate these steps.
[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 document.
responseText attributeresponseTextReturns the text response entity body.
The
responseText
attribute must return the result of running these
steps:
If the state is not LOADING or DONE return the empty string and terminate these steps.
If the error flag is true return the empty string and terminate these steps.
Return the text response entity body.
responseXML attributeresponseXMLReturns the document response entity body.
The
responseXML
attribute must return the result of running these steps:
If the state is not DONE return null and terminate these steps.
If the error flag is true return null and terminate these steps.
Return the document response entity body.
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, Chris Marrin, Christophe Jolif, Charles McCathieNevile, Dan Winship, David Andersson, David Flanagan, David Håsäther, David Levin, Dean Jackson, Denis Sureau, Doug Schepers, Douglas Livingstone, Elliotte Harold, Eric Lawrence, Eric Uhrhane, Erik Dahlström, Geoffrey Sneddon, Gideon Cohn, Gorm Haug Eriksen, Håkon Wium Lie, Hallvord R. M. Steen, Henri Sivonen, Huub Schaeks, Ian Davis, Ian Hickson, Ivan Herman, Jeff Walden, Jens Lindström, Jim Deegan, Jim Ley, Joe Farro, Jonas Sicking, Julian Reschke, Karl Dubost, Lachlan Hunt, Maciej Stachowiak, Magnus Kristiansen, Marc Hadley, Marcos Caceres, Mark Baker, Mark Birbeck, Mark Nottingham, Mark S. Miller, Martin Hassman, Mohamed Zergaoui, Ms2ger, Odin Hørthe Omdal, Olli Pettay, Pawel Glowacki, Peter Michaux, Philip Taylor, Robin Berjon, Rune Halvorsen, Ruud Steltenpool, Sergiu Dumitriu, Sigbjørn Finne, Simon Pieters, Stewart Brodie, Sunava Dutta, Thomas Roessler, 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). [HTML]
Thanks also to all those who have helped to improve this specification by sending suggestions and corrections. (Please, keep bugging us with your issues!)