1.Introduction
This section is non-normative.
TheXMLHttpRequest
object is an API forfetchingresources.
The nameXMLHttpRequest
is historical and has no bearing on its functionality.
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 . status== 200 &&
this . responseXML!= null &&
this . responseXML. getElementById( 'test' ). textContent) {
// success!
processData( this . responseXML. getElementById( 'test' ). textContent);
} else {
// something went wrong
…
}
}
var client= new XMLHttpRequest();
client. onload= 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. onload= function () {
// in case of network errors this might not give reliable results
returnStatus( this . status);
}
client. open( "HEAD" , address);
client. send();
}
1.1.Specification history
TheXMLHttpRequest
object was initially defined as part of
the WHATWG’s HTML effort. (Based on Microsoft’s implementation many years prior.)
It moved to the W3C in 2006. Extensions (e.g., progress events and
cross-origin requests) toXMLHttpRequest
were developed in a
separate draft (XMLHttpRequest Level 2) until end of 2011, at which point
the two drafts were merged andXMLHttpRequest
became a single
entity again from a standards perspective. End of 2012 it moved back to the
WHATWG.
Discussion that led to the current draft can be found in the following mailing list archives:
2.Terminology
This specification depends on the Infra Standard.[INFRA]
This specification uses terminology from DOM, DOM Parsing and Serialization, Encoding, Fetch, File API, HTML, URL, Web IDL, and XML.
[DOM][DOM-PARSING][ENCODING][FETCH][FILEAPI][HTML][URL][WEBIDL][XML][XML-NAMES]
3.InterfaceXMLHttpRequest
[Exposed =(Window ,DedicatedWorker ,SharedWorker )]interface :
XMLHttpRequestEventTarget EventTarget { // event handlersattribute EventHandler onloadstart ;attribute EventHandler onprogress ;attribute EventHandler onabort ;attribute EventHandler onerror ;attribute EventHandler onload ;attribute EventHandler ontimeout ;attribute EventHandler onloadend ; }; [Exposed =(Window ,DedicatedWorker ,SharedWorker )]interface :
XMLHttpRequestUpload XMLHttpRequestEventTarget { };enum {
XMLHttpRequestResponseType ,
"" ,
"arraybuffer" ,
"blob" ,
"document" ,
"json" }; [
"text" Exposed =(Window ,DedicatedWorker ,SharedWorker )]interface :
XMLHttpRequest XMLHttpRequestEventTarget {constructor (); // event handlerattribute EventHandler onreadystatechange ; // statesconst 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 ; // requestundefined open (ByteString ,
method USVString );
url undefined open (ByteString ,
method USVString ,
url boolean ,
async optional USVString ?=
username null ,optional USVString ?=
password null );undefined setRequestHeader (ByteString ,
name ByteString );
value attribute unsigned long timeout ;attribute boolean withCredentials ; [SameObject ]readonly attribute XMLHttpRequestUpload upload ;undefined send (optional (Document or XMLHttpRequestBodyInit )?=
body null );undefined abort (); // responsereadonly attribute USVString responseURL ;readonly attribute unsigned short status ;readonly attribute ByteString statusText ;ByteString ?getResponseHeader (ByteString );
name ByteString getAllResponseHeaders ();undefined overrideMimeType (DOMString );
mime attribute XMLHttpRequestResponseType responseType ;readonly attribute any response ;readonly attribute USVString responseText ; [Exposed =Window ]readonly attribute Document ?responseXML ; };
AnXMLHttpRequest
object has an associated:
- upload object
- An
XMLHttpRequestUpload
object. - state
- One ofunsent,opened,headers received,loading,anddone; initiallyunsent.
send()
flag- A flag, initially unset.
- timeout
- An unsigned integer, initially 0.
- cross-origin credentials
- A boolean, initially false.
- request method
- Amethod.
- request URL
- AURL.
- author request headers
- Aheader list,initially empty.
- request body
- Initially null.
- synchronous flag
- A flag, initially unset.
- upload complete flag
- A flag, initially unset.
- upload listener flag
- A flag, initially unset.
- timed out flag
- A flag, initially unset.
- response
- Aresponse,initially anetwork error.
- received bytes
- Abyte sequence,initially the empty byte sequence.
- response type
- One of the empty string, "
arraybuffer
","blob
", "document
","json
",and"text
";initially the empty string. - response object
- An object, failure, or null, initially null.
- fetch controller
- Afetch controller,initially a newfetch controller.The
send()
method sets it to a usefulfetch controller,but for simplicity it always holds afetch controller. - override MIME type
- AMIME typeor null, initially null.Can get a value when
overrideMimeType()
is invoked.
3.1.Constructors
client= newXMLHttpRequest()
- Returns a new
XMLHttpRequest
object.
Thenew XMLHttpRequest()
constructor steps are:
-
Setthis’supload objectto anew
XMLHttpRequestUpload
object.
3.2.Garbage collection
AnXMLHttpRequest
object must not be garbage collected if itsstateis eitheropenedwith thesend()
flagset,headers received,orloading,and it has one or moreevent listenersregistered whosetypeis one ofreadystatechange
,progress
,abort
,error
,load
,timeout
,andloadend
.
If anXMLHttpRequest
object is garbage collected while its connection is still open, the user
agent mustterminatetheXMLHttpRequest
object’sfetch controller.
3.3.Event handlers
The following are theevent handlers(and their correspondingevent handler event types)
that must be supported on objects implementing an interface that inherits
fromXMLHttpRequestEventTarget
as attributes:
event handler | event handler event type |
---|---|
onloadstart
| loadstart
|
onprogress
| progress
|
onabort
| abort
|
onerror
| error
|
onload
| load
|
ontimeout
| timeout
|
onloadend
| loadend
|
The following is theevent handler(and its correspondingevent handler event type) that must be
supported as attribute solely by theXMLHttpRequest
object:
event handler | event handler event type |
---|---|
onreadystatechange
| readystatechange
|
3.4.States
client.readyState
-
Returnsclient’sstate.
ThereadyState
getter steps are to return
the value from the table below in the cell of the second column, from the row where the value in the
cell in the first column isthis’sstate:
unsent | UNSENT (numeric value 0)
| The object has been constructed. |
opened | OPENED (numeric value 1)
| Theopen() method has
been successfully invoked. During this state request headers can be set usingsetRequestHeader() and the fetch can be initiated using thesend() method.
|
headers received | HEADERS_RECEIVED (numeric value 2)
| All redirects (if any) have been followed and all headers of a response have been received. |
loading | LOADING (numeric value 3)
| The response body is being received. |
done | DONE (numeric value 4)
| The data transfer has been completed or something went wrong during the transfer (e.g., infinite redirects). |
3.5.Request
Registering one or more event listeners on anXMLHttpRequestUpload
object will result in aCORS-preflight request.(That is because
registering an event listener causes theupload listener flagto be set, which in turn causes
theuse-CORS-preflight flagto be set.)
3.5.1.Theopen()
method
client.open(method,url[,async= true [,username= null [,password= null]]])
-
Sets therequest method,request URL,andsynchronous flag.
Throws a "
SyntaxError
"DOMException
if eithermethodis not a valid method orurlcannot be parsed.Throws a "
SecurityError
"DOMException
ifmethodis a case-insensitive match for `CONNECT
`, `TRACE
`, or `TRACK
`.Throws an "
InvalidAccessError
"DOMException
ifasyncis false, thecurrent global objectis aWindow
object, and thetimeout
attribute is not zero or theresponseType
attribute is not the empty string.
SynchronousXMLHttpRequest
outside of workers is in the
process of being removed from the web platform as it has detrimental effects to the end user’s
experience. (This is a long process that takes many years.) Developers must not pass false for theasyncargument when thecurrent global objectis aWindow
object. User agents
are strongly encouraged to warn about such usage in developer tools and may experiment withthrowingan "InvalidAccessError
"DOMException
when it occurs.
Theopen(method,url)
andopen(method,url,async,username,password)
method steps are:
-
Ifthis’srelevant global objectis a
Window
object and itsassociatedDocument
is notfully active,thenthrowan "InvalidStateError
"DOMException
. -
Ifmethodis not amethod,thenthrowa "
SyntaxError
"DOMException
. -
Ifmethodis aforbidden method,thenthrowa "
SecurityError
"DOMException
. -
Normalizemethod.
-
LetparsedURLbe the result ofencoding-parsing a URLurl,relative tothis’srelevant settings object.
-
IfparsedURLis failure, thenthrowa "
SyntaxError
"DOMException
. -
If theasyncargument is omitted, setasyncto true, and setusernameandpasswordto null.
Unfortunately legacy content prevents treating theasyncargument being
undefined
identical from it being omitted. -
IfparsedURL’shostis non-null, then:
-
If theusernameargument is not null,set the usernamegivenparsedURLandusername.
-
If thepasswordargument is not null,set the passwordgivenparsedURLandpassword.
-
-
Ifasyncis false, thecurrent global objectis a
Window
object, and eitherthis’stimeoutis not 0 orthis’sresponse typeis not the empty string, thenthrowan "InvalidAccessError
"DOMException
. -
Terminatethis’sfetch controller.
Afetchcan be ongoing at this point.
-
Set variables associated with the object as follows:
-
Unsetthis’s
send()
flag. -
Unsetthis’supload listener flag.
-
Setthis’srequest methodtomethod.
-
Setthis’srequest URLtoparsedURL.
-
Setthis’ssynchronous flagifasyncis false; otherwise unsetthis’ssynchronous flag.
-
Setthis’sresponseto anetwork error.
-
Setthis’sreceived bytesto the empty byte sequence.
-
Setthis’sresponse objectto null.
Override MIME typeis not overridden here as the
overrideMimeType()
method can be invoked before theopen()
method. -
-
Ifthis’sstateis notopened,then:
The reason there are twoopen()
methods defined is due to a limitation of
the editing software used to write the XMLHttpRequest Standard.
3.5.2.ThesetRequestHeader()
method
client.setRequestHeader(name,value)
-
Appends a value to an existing request header or adds a new request header.
Throws an "
InvalidStateError
"DOMException
if eitherstateis notopenedor thesend()
flagis set.Throws a "
SyntaxError
"DOMException
ifnameis not a header name or ifvalueis not a header value.
ThesetRequestHeader(name,value)
method must run these steps:
-
Ifthis’sstateis notopened,thenthrowan "
InvalidStateError
"DOMException
. -
Ifthis’s
send()
flagis set, thenthrowan "InvalidStateError
"DOMException
. -
Normalizevalue.
-
Ifnameis not aheader nameorvalueis not aheader value,thenthrowa "
SyntaxError
"DOMException
.An empty byte sequence represents an emptyheader value.
-
If (name,value) is aforbidden request-header,then return.
-
Combine(name,value) inthis’sauthor request headers.
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
3.5.3.Thetimeout
getter and setter
client.timeout
-
Can be set to a time in milliseconds. When set to a non-zero value will causefetchingto terminate after the given time has passed. When the time has passed, the request has not yet completed, andthis’ssynchronous flagis unset, a
timeout
event will then bedispatched,or a "TimeoutError
"DOMException
will bethrownotherwise (for thesend()
method).When set: throws an "
InvalidAccessError
"DOMException
if thesynchronous flagis set and thecurrent global objectis aWindow
object.
Thetimeout
getter steps are to returnthis’stimeout.
Thetimeout
setter steps are:
-
If thecurrent global objectis a
Window
object andthis’ssynchronous flagis set, thenthrowan "InvalidAccessError
"DOMException
.
This implies that thetimeout
attribute can be
set whilefetchingis in
progress. If that occurs it will still be measured relative to the start
offetching.
3.5.4.ThewithCredentials
getter and setter
client.withCredentials
-
True whencredentialsare to be included in a cross-origin request. False when they are to be excluded in a cross-origin request and when cookies are to be ignored in its response. Initially false.
When set: throws an "
InvalidStateError
"DOMException
ifstateis notunsentoropened,or if thesend()
flagis set.
ThewithCredentials
getter steps are to
returnthis’scross-origin credentials.
ThewithCredentials
setter steps are:
-
Ifthis’sstateis notunsentoropened,thenthrowan "
InvalidStateError
"DOMException
. -
Ifthis’s
send()
flagis set, thenthrowan "InvalidStateError
"DOMException
. -
Setthis’scross-origin credentialsto the given value.
3.5.5.Theupload
getter
client.upload
-
Returns the associated
XMLHttpRequestUpload
object. It can be used to gather transmission information when data is transferred to a server.
Theupload
getter steps are to returnthis’supload object.
3.5.6.Thesend()
method
client.send([body= null])
-
Initiates the request. Thebodyargument provides therequest body,if any, and is ignored if therequest methodis
GET
orHEAD
.Throws an "
InvalidStateError
"DOMException
if eitherstateis notopenedor thesend()
flagis set.
Thesend(body)
method steps are:
-
Ifthis’sstateis notopened,thenthrowan "
InvalidStateError
"DOMException
. -
Ifthis’s
send()
flagis set, thenthrowan "InvalidStateError
"DOMException
. -
Ifthis’srequest methodis `
GET
` or `HEAD
`, then setbodyto null. -
Ifbodyis not null, then:
-
LetextractedContentTypebe null.
-
Ifbodyis a
Document
,then setthis’srequest bodytobody,serialized,converted,andUTF-8 encoded. -
Otherwise:
-
LetbodyWithTypebe the result ofsafely extractingbody.
-
Setthis’srequest bodytobodyWithType’sbody.
-
SetextractedContentTypetobodyWithType’stype.
-
-
LetoriginalAuthorContentTypebe the result ofgetting`
Content-Type
` fromthis’sauthor request headers. -
IforiginalAuthorContentTypeis non-null, then:
-
Ifbodyis a
Document
or aUSVString
,then:-
LetcontentTypeRecordbe the result ofparsingoriginalAuthorContentType.
-
IfcontentTypeRecordis not failure,contentTypeRecord’sparameters[ "
charset
"]exists,andparameters[ "charset
"] is not anASCII case-insensitivematch for "UTF-8
",then:-
SetcontentTypeRecord’sparameters[ "
charset
"] to"UTF-8
". -
LetnewContentTypeSerializedbe the result ofserializingcontentTypeRecord.
-
Set(`
Content-Type
`,newContentTypeSerialized) inthis’sauthor request headers.
-
-
-
-
Otherwise:
-
Ifbodyis anHTML document,thenset(`
Content-Type
`, `text/html;charset=UTF-8
`) inthis’sauthor request headers. -
Otherwise, ifbodyis anXML document,set(`
Content-Type
`, `application/xml;charset=UTF-8
`) inthis’sauthor request headers. -
Otherwise, ifextractedContentTypeis not null,set(`
Content-Type
`,extractedContentType) inthis’sauthor request headers.
-
-
-
If one or more event listeners are registered onthis’supload object,then setthis’supload listener flag.
-
Letreqbe a newrequest,initialized as follows:
- method
- This’srequest method.
- URL
- This’srequest URL.
- header list
- This’sauthor request headers.
- unsafe-request flag
- Set.
- body
- This’srequest body.
- client
- This’srelevant settings object.
- mode
- "
cors
". - use-CORS-preflight flag
- Set ifthis’supload listener flagis set.
- credentials mode
- Ifthis’scross-origin credentialsis true, then "
include
"; otherwise"same-origin
". - use-URL-credentials flag
- Set ifthis’srequest URLincludes credentials.
- initiator type
- "
xmlhttprequest
".
-
Unsetthis’supload complete flag.
-
Unsetthis’stimed out flag.
-
Ifreq’sbodyis null, then setthis’supload complete flag.
-
Setthis’s
send()
flag. -
Ifthis’ssynchronous flagis unset, then:
-
Fire a progress eventnamed
loadstart
atthiswith 0 and 0. -
LetrequestBodyTransmittedbe 0.
-
LetrequestBodyLengthbereq’sbody’slength,ifreq’sbodyis non-null; otherwise 0.
-
Assert:requestBodyLengthis an integer.
-
Ifthis’supload complete flagis unset andthis’supload listener flagis set, thenfire a progress eventnamed
loadstart
atthis’supload objectwithrequestBodyTransmittedandrequestBodyLength. -
Ifthis’sstateis notopenedorthis’s
send()
flagis unset, then return. -
LetprocessRequestBodyChunkLength,given abytesLength,be these steps:
-
IncreaserequestBodyTransmittedbybytesLength.
-
If not roughly 50ms have passed since these steps were last invoked, then return.
-
Ifthis’supload listener flagis set, thenfire a progress eventnamed
progress
atthis’supload objectwithrequestBodyTransmittedandrequestBodyLength.
These steps are only invoked when new bytes are transmitted.
-
-
LetprocessRequestEndOfBodybe these steps:
-
Setthis’supload complete flag.
-
Ifthis’supload listener flagis unset, then return.
-
Fire a progress eventnamed
progress
atthis’supload objectwithrequestBodyTransmittedandrequestBodyLength. -
Fire a progress eventnamed
load
atthis’supload objectwithrequestBodyTransmittedandrequestBodyLength. -
Fire a progress eventnamed
loadend
atthis’supload objectwithrequestBodyTransmittedandrequestBodyLength.
-
-
LetprocessResponse,given aresponse,be these steps:
-
Ifthis’sresponseis anetwork error,then return.
-
Ifthis’sresponse’sbodyis null, then runhandle response end-of-bodyforthisand return.
-
Letlengthbe the result ofextracting a lengthfromthis’sresponse’sheader list.
-
Iflengthis not an integer, then set it to 0.
-
LetprocessBodyChunkgivenbytesbe these steps:
-
Appendbytestothis’sreceived bytes.
-
If not roughly 50ms have passed since these steps were last invoked, then return.
-
Ifthis’sstateisheaders received,then setthis’sstatetoloading.
-
Fire an eventnamed
readystatechange
atthis.Web compatibility is the reason
readystatechange
fires more often thanthis’sstatechanges. -
Fire a progress eventnamed
progress
atthiswiththis’sreceived bytes’slengthandlength.
-
-
LetprocessEndOfBodybe this step: runhandle response end-of-bodyforthis.
-
LetprocessBodyErrorbe these steps:
-
Setthis’sresponseto anetwork error.
-
Runhandle errorsforthis.
-
-
Incrementally readthis’sresponse’sbody,givenprocessBodyChunk,processEndOfBody,processBodyError,andthis’srelevant global object.
-
Setthis’sfetch controllerto the result offetchingreqwithprocessRequestBodyChunkLengthset toprocessRequestBodyChunkLength,processRequestEndOfBodyset toprocessRequestEndOfBody,andprocessResponseset toprocessResponse.
-
Letnowbe the present time.
-
Run these stepsin parallel:
-
-
Otherwise, ifthis’ssynchronous flagis set:
-
LetprocessedResponsebe false.
-
LetprocessResponseConsumeBody,given aresponseandnullOrFailureOrBytes,be these steps:
-
IfnullOrFailureOrBytesis not failure, then setthis’sresponsetoresponse.
-
IfnullOrFailureOrBytesis abyte sequence,then appendnullOrFailureOrBytestothis’sreceived bytes.
-
SetprocessedResponseto true.
-
-
Setthis’sfetch controllerto the result offetchingreqwithprocessResponseConsumeBodyset toprocessResponseConsumeBodyanduseParallelQueueset to true.
-
Letnowbe the present time.
-
Pauseuntil eitherprocessedResponseis true orthis’stimeoutis not 0 andthis’stimeoutmilliseconds have passed sincenow.
-
IfprocessedResponseis false, then setthis’stimed out flagandterminatethis’sfetch controller.
-
Report timingforthis’sfetch controllergiven thecurrent global object.
-
Tohandle response end-of-bodyfor anXMLHttpRequest
objectxhr,run these steps:
-
Handle errorsforxhr.
-
Ifxhr’sresponseis anetwork error,then return.
-
Lettransmittedbexhr’sreceived bytes’slength.
-
Letlengthbe the result ofextracting a lengthfromthis’sresponse’sheader list.
-
Iflengthis not an integer, then set it to 0.
-
Ifxhr’ssynchronous flagis unset, thenfire a progress eventnamed
progress
atxhrwithtransmittedandlength. -
Setxhr’sstatetodone.
-
Unsetxhr’s
send()
flag. -
Fire an eventnamed
readystatechange
atxhr. -
Fire a progress eventnamed
load
atxhrwithtransmittedandlength. -
Fire a progress eventnamed
loadend
atxhrwithtransmittedandlength.
Tohandle errorsfor anXMLHttpRequest
objectxhr,run these steps:
-
Ifxhr’s
send()
flagis unset, then return. -
Ifxhr’stimed out flagis set, then run therequest error stepsforxhr,
timeout
,and "TimeoutError
"DOMException
. -
Otherwise, ifxhr’sresponse’saborted flagis set, run therequest error stepsforxhr,
abort
,and "AbortError
"DOMException
. -
Otherwise, ifxhr’sresponseis anetwork error,then run therequest error stepsforxhr,
error
,and "NetworkError
"DOMException
.
Therequest error stepsfor anXMLHttpRequest
objectxhr,event,and optionallyexceptionare:
-
Setxhr’sstatetodone.
-
Unsetxhr’s
send()
flag. -
Setxhr’sresponseto anetwork error.
-
Ifxhr’ssynchronous flagis set, thenthrowexception.
-
Fire an eventnamed
readystatechange
atxhr.At this point it is clear thatxhr’ssynchronous flagis unset.
-
Ifxhr’supload complete flagis unset, then:
-
Setxhr’supload complete flag.
-
Ifxhr’supload listener flagis set, then:
-
Fire a progress eventnamedeventatxhr’supload objectwith 0 and 0.
-
Fire a progress eventnamed
loadend
atxhr’supload objectwith 0 and 0.
-
-
-
Fire a progress eventnamedeventatxhrwith 0 and 0.
-
Fire a progress eventnamed
loadend
atxhrwith 0 and 0.
3.5.7.Theabort()
method
client.abort()
- Cancels any network activity.
Theabort()
method steps are:
-
Ifthis’sstateisopenedwiththis’s
send()
flagset,headers received,orloading,then run therequest error stepsforthisandabort
. -
Ifthis’sstateisdone,then setthis’sstatetounsentandthis’sresponseto anetwork error.
No
readystatechange
event is dispatched.
3.6.Response
3.6.1.TheresponseURL
getter
TheresponseURL
getter steps are to return
the empty string ifthis’sresponse’sURLis
null; otherwise itsserializationwith theexclude fragment flagset.
3.6.2.Thestatus
getter
Thestatus
getter steps are to returnthis’sresponse’sstatus.
3.6.3.ThestatusText
getter
ThestatusText
getter steps are to returnthis’sresponse’sstatus message.
3.6.4.ThegetResponseHeader()
method
ThegetResponseHeader(name)
method
steps are to return the result ofgettingnamefromthis’sresponse’sheader list.
The Fetch Standard filtersthis’sresponse’sheader list.[FETCH]
For the following script:
var client= new XMLHttpRequest();
client. open( "GET" , "unicorns-are-awesome.txt" , true );
client. send();
client. onreadystatechange= function () {
if ( this . readyState== this . HEADERS_RECEIVED) {
print( client. getResponseHeader( "Content-Type" ));
}
}
Theprint()
function will get to process something like:
text/plain; charset=UTF-8
3.6.5.ThegetAllResponseHeaders()
method
Abyte sequenceaislegacy-uppercased-byte less thanabyte sequencebif the following steps return true:
-
LetAbea,byte-uppercased.
-
LetBbeb,byte-uppercased.
-
ReturnAisbyte less thanB.
ThegetAllResponseHeaders()
method steps are:
-
Letoutputbe an empty byte sequence.
-
LetinitialHeadersbe the result of runningsort and combinewiththis’sresponse’sheader list.
-
Letheadersbe the result ofsortinginitialHeadersin ascending order, withabeing less thanbifa’snameislegacy-uppercased-byte less thanb’sname.
Unfortunately, this is needed for compatibility with deployed content.
-
For eachheaderinheaders,appendheader’sname,followed by a 0x3A 0x20 byte pair, followed byheader’svalue,followed by a 0x0D 0x0A byte pair, tooutput.
-
Returnoutput.
The Fetch Standard filtersthis’sresponse’sheader list.[FETCH]
For the following script:
var client= new XMLHttpRequest();
client. open( "GET" , "narwhals-too.txt" , true );
client. send();
client. onreadystatechange= function () {
if ( this . readyState== this . HEADERS_RECEIVED) {
print( this . getAllResponseHeaders());
}
}
Theprint()
function will get to process something
like:
connection: Keep-Alive
content-type: text/plain; charset=utf-8
date: Sun, 24 Oct 2004 04:58:38 GMT
keep-alive: timeout=15, max=99
server: Apache/1.3.31 (Unix)
transfer-encoding: chunked
3.6.6.Response body
Toget a response MIME typefor anXMLHttpRequest
objectxhr,run these steps:
-
LetmimeTypebe the result ofextracting a MIME typefromxhr’sresponse’sheader list.
-
IfmimeTypeis failure, then setmimeTypeto
text/xml
. -
ReturnmimeType.
Toget a final MIME typefor anXMLHttpRequest
objectxhr,run these steps:
-
Ifxhr’soverride MIME typeis null, return the result ofget a response MIME typeforxhr.
-
Returnxhr’soverride MIME type.
Toget a final encodingfor anXMLHttpRequest
objectxhr,run these steps:
-
Letlabelbe null.
-
LetresponseMIMEbe the result ofget a response MIME typeforxhr.
-
IfresponseMIME’sparameters[ "
charset
"]exists,then setlabelto it. -
Ifxhr’soverride MIME type’sparameters[ "
charset
"]exists,then setlabelto it. -
Iflabelis null, then return null.
-
Letencodingbe the result ofgetting an encodingfromlabel.
-
Ifencodingis failure, then return null.
-
Returnencoding.
The above steps intentionally do not use theget a final MIME typeas it would not be web compatible.
Toset a document responsefor anXMLHttpRequest
objectxhr,run these steps:
-
LetfinalMIMEbe the result ofget a final MIME typeforxhr.
-
IffinalMIMEis not anHTML MIME typeor anXML MIME type,then return.
-
Ifxhr’sresponse typeis the empty string andfinalMIMEis anHTML MIME type,then return.
This is restricted toxhr’sresponse typebeing "
document
"in order to prevent breaking legacy content. -
IffinalMIMEis anHTML MIME type,then:
-
Letcharsetbe the result ofget a final encodingforxhr.
-
Ifcharsetis null,prescanthe first 1024 bytes ofxhr’sreceived bytesand if that does not terminate unsuccessfully then letcharsetbe the return value.
-
Ifcharsetis null, then setcharsettoUTF-8.
-
Letdocumentbe adocumentthat represents the result parsingxhr’sreceived bytesfollowing the rules set forth in the HTML Standard for an HTML parser with scripting disabled anda known definite encodingcharset.[HTML]
-
Flagdocumentas anHTML document.
-
-
Otherwise, letdocumentbe adocumentthat represents the result of running theXML parserwithXML scripting support disabledonxhr’sreceived bytes.If that fails (unsupported character encoding, namespace well-formedness error, etc.), then return null.[HTML]
Resources referenced will not be loaded and no associated XSLT will be applied.
-
Ifcharsetis null, then setcharsettoUTF-8.
-
Setdocument’sencodingtocharset.
-
Setdocument’scontent typetofinalMIME.
-
Setdocument’sorigintoxhr’srelevant settings object’sorigin.
-
Setxhr’sresponse objecttodocument.
Toget a text responsefor anXMLHttpRequest
objectxhr,run these steps:
-
Letcharsetbe the result ofget a final encodingforxhr.
-
Ifxhr’sresponse typeis the empty string,charsetis null, and the result ofget a final MIME typeforxhris anXML MIME type,then use the rules set forth in the XML specifications to determine the encoding. Letcharsetbe the determined encoding.[XML][XML-NAMES]
This is restricted toxhr’sresponse typebeing the empty string to keep the non-legacyresponse typevalue "
text
"simple. -
Ifcharsetis null, then setcharsettoUTF-8.
-
Return the result of runningdecodeonxhr’sreceived bytesusing fallback encodingcharset.
Authors are strongly encouraged to always encode their resources usingUTF-8.
3.6.7.TheoverrideMimeType()
method
client.overrideMimeType(mime)
-
Acts as if the `
Content-Type
` header value for a response ismime.(It does not change the header.)Throws an "
InvalidStateError
"DOMException
ifstateisloadingordone.
TheoverrideMimeType(mime)
method
steps are:
-
Ifthis’sstateisloadingordone,thenthrowan "
InvalidStateError
"DOMException
. -
Setthis’soverride MIME typeto the result ofparsingmime.
-
Ifthis’soverride MIME typeis failure, then setthis’soverride MIME typeto
application/octet-stream
.
3.6.8.TheresponseType
getter and setter
client.responseType[ =value]
-
Returns the response type.
Can be set to change the response type. Values are: the empty string (default), "
arraybuffer
", "blob
", "document
", "json
",and "text
".When set: setting to "
document
"is ignored if thecurrent global objectis not aWindow
object.When set: throws an "
InvalidStateError
"DOMException
ifstateisloadingordone.When set: throws an "
InvalidAccessError
"DOMException
if thesynchronous flagis set and thecurrent global objectis aWindow
object.
TheresponseType
getter steps are to returnthis’sresponse type.
TheresponseType
setter steps are:
-
If thecurrent global objectis not a
Window
object and the given value is "document
",then return. -
Ifthis’sstateisloadingordone,thenthrowan "
InvalidStateError
"DOMException
. -
If thecurrent global objectis a
Window
object andthis’ssynchronous flagis set, thenthrowan "InvalidAccessError
"DOMException
. -
Setthis’sresponse typeto the given value.
3.6.9.Theresponse
getter
client.response
-
Returns the response body.
Theresponse
getter steps are:
-
Ifthis’sresponse typeis the empty string or "
text
",then:-
Ifthis’sstateis notloadingordone,then return the empty string.
-
Return the result ofgetting a text responseforthis.
-
-
Ifthis’sresponse objectis failure, then return null.
-
Ifthis’sresponse objectis non-null, then return it.
-
Ifthis’sresponse typeis "
arraybuffer
",then setthis’sresponse objectto anewArrayBuffer
object representingthis’sreceived bytes.If this throws an exception, then setthis’sresponse objectto failure and return null.Allocating an
ArrayBuffer
object is not guaranteed to succeed.[ECMASCRIPT] -
Otherwise, ifthis’sresponse typeis "
blob
", setthis’sresponse objectto anewBlob
object representingthis’sreceived byteswithtype
set to the result ofget a final MIME typeforthis. -
Otherwise, ifthis’sresponse typeis "
document
",set a document responseforthis. -
Otherwise:
-
Assert:this’sresponse typeis "
json
". -
LetjsonObjectbe the result of runningparse JSON from bytesonthis’sreceived bytes.If that threw an exception, then return null.
-
Setthis’sresponse objecttojsonObject.
-
-
Returnthis’sresponse object.
3.6.10.TheresponseText
getter
client.responseText
-
Returns response as text.
Throws an "
InvalidStateError
"DOMException
ifresponseType
is not the empty string or "text
".
TheresponseText
getter steps are:
-
Ifthis’sresponse typeis not the empty string or "
text
",thenthrowan "InvalidStateError
"DOMException
. -
Ifthis’sstateis notloadingordone,then return the empty string.
-
Return the result ofgetting a text responseforthis.
3.6.11.TheresponseXML
getter
client.responseXML
-
Returns the response as document.
Throws an "
InvalidStateError
"DOMException
ifresponseType
is not the empty string or "document
".
TheresponseXML
getter steps are:
-
Ifthis’sresponse typeis not the empty string or "
document
", thenthrowan "InvalidStateError
"DOMException
. -
Assert:this’sresponse objectis not failure.
-
Ifthis’sresponse objectis non-null, then return it.
-
Returnthis’sresponse object.
3.7.Events summary
This section is non-normative.
The following events are dispatched onXMLHttpRequest
orXMLHttpRequestUpload
objects:
Event name | Interface | Dispatched when… |
---|---|---|
readystatechange
| Event
| ThereadyState attribute changes
value, except when it changes toUNSENT.
|
loadstart
| ProgressEvent
| The fetch initiates. |
progress
| ProgressEvent
| Transmitting data. |
abort
| ProgressEvent
| When the fetch has been aborted. For instance, by invoking theabort() method.
|
error
| ProgressEvent
| The fetch failed. |
load
| ProgressEvent
| The fetch succeeded. |
timeout
| ProgressEvent
| The author specified timeout has passed before the fetch completed. |
loadend
| ProgressEvent
| The fetch completed (success or failure). |
4.InterfaceFormData
typedef (File or USVString ); [
FormDataEntryValue Exposed =(Window ,Worker )]interface {
FormData constructor (optional HTMLFormElement ,
form optional HTMLElement ?=
submitter null );undefined append (USVString ,
name USVString );
value undefined append (USVString ,
name Blob ,
blobValue optional USVString );
filename undefined delete (USVString );
name FormDataEntryValue ?get (USVString );
name sequence <FormDataEntryValue >getAll (USVString );
name boolean has (USVString );
name undefined set (USVString ,
name USVString );
value undefined set (USVString ,
name Blob ,
blobValue optional USVString );
filename iterable <USVString ,FormDataEntryValue >; };
EachFormData
object has an associatedentry list(anentry list). It is initially empty.
This section used to defineentry,an entry’snameandvalue,and thecreate an entryalgorithm. These definitions have been moved to the HTML Standard.[HTML]
Thenew FormData(form,submitter)
constructor steps are:
-
Ifformis given, then:
-
Ifsubmitteris non-null, then:
-
Ifsubmitteris not asubmit button,thenthrowa
TypeError
. -
Ifsubmitter’sform owneris notform,thenthrowa "
NotFoundError
"DOMException
.
-
-
Letlistbe the result ofconstructing the entry listforformandsubmitter.
-
Iflistis null, thenthrowan "
InvalidStateError
"DOMException
. -
Setthis’sentry listtolist.
-
Theappend(name,value)
andappend(name,blobValue,filename)
method steps are:
-
Letvaluebevalueif given; otherwiseblobValue.
-
Letentrybe the result ofcreating an entrywithname,value,andfilenameif given.
-
Appendentrytothis’sentry list.
The reason there is an argument namedvalueas well asblobValueis due to a limitation of the editing software used to write the XMLHttpRequest Standard.
Thedelete(name)
method steps are toremoveallentrieswhosenameisnamefromthis’sentry list.
Theget(name)
method
steps are:
-
If there is noentrywhosenameisnameinthis’sentry list,then return null.
-
Return thevalueof the firstentrywhosenameisnamefromthis’sentry list.
ThegetAll(name)
method steps are:
-
If there is noentrywhosenameisnameinthis’sentry list,then return the empty list.
-
Return thevaluesof allentrieswhosenameisname,in order, fromthis’sentry list.
Thehas(name)
method
steps are to return true if there is anentrywhosenameisnameinthis’sentry list;otherwise false.
Theset(name,value)
andset(name,blobValue,filename)
method steps are:
-
Letvaluebevalueif given; otherwiseblobValue.
-
Letentrybe the result ofcreating an entrywithname,value,andfilenameif given.
-
If there areentriesinthis’sentry listwhosenameisname,thenreplacethe first suchentrywithentryandremovethe others.
-
Otherwise,appendentrytothis’sentry list.
The reason there is an argument namedvalueas well asblobValueis due to a limitation of the editing software used to write the XMLHttpRequest Standard.
Thevalue pairs to iterate overarethis’sentry list’sentrieswith the key being thenameand the value being thevalue.
5.InterfaceProgressEvent
[Exposed =(Window ,Worker )]interface :
ProgressEvent Event {(
constructor DOMString ,
type optional ProgressEventInit = {});
eventInitDict readonly attribute boolean lengthComputable ;readonly attribute unsigned long long loaded ;readonly attribute unsigned long long total ; };dictionary :
ProgressEventInit EventInit {boolean =
lengthComputable false ;unsigned long long = 0;
loaded unsigned long long = 0; };
total
Eventsusing theProgressEvent
interface indicate some kind of progression.
ThelengthComputable
,loaded
,andtotal
getter steps are to return the value they were initialized to.
5.1.Firing events using theProgressEvent
interface
Tofire a progress eventnamedeattarget,giventransmittedandlength,means tofire an eventnamedeattarget,usingProgressEvent
,with theloaded
attribute initialized totransmitted,and iflengthis not 0, with thelengthComputable
attribute initialized to true and thetotal
attribute initialized tolength.
5.2.Suggested names for events using theProgressEvent
interface
This section is non-normative.
The suggestedtype
attribute values for use witheventsusing theProgressEvent
interface are summarized in the table below.
Specification editors are free to tune the details to their specific
scenarios, though are strongly encouraged to discuss their usage with the
WHATWG community to ensure input from people familiar with the subject.
type attribute value
| Description | Times | When |
---|---|---|---|
loadstart
| Progress has begun. | Once. | First. |
progress
| In progress. | Once or more. | Afterloadstart has beendispatched.
|
error
| Progression failed. | Zero or once (mutually exclusive). | After the lastprogress has
beendispatched.
|
abort
| Progression is terminated. | ||
timeout
| Progression is terminated due to preset time expiring. | ||
load
| Progression is successful. | ||
loadend
| Progress has stopped. | Once. | After one oferror ,abort ,timeout orload has beendispatched.
|
Theerror
,abort
,timeout
,andload
event types are mutually exclusive.
Throughout the web platform theerror
,abort
,timeout
andload
event types have
theirbubbles
andcancelable
attributes initialized to false, so it is suggested that for consistency alleventsusing theProgressEvent
interface do the same.
5.3.Security considerations
For cross-origin requests some kind of opt-in, e.g., theCORS protocoldefined in the Fetch Standard, has to be
used beforeeventsusing theProgressEvent
interface aredispatchedas information (e.g., size) would be revealed that cannot be obtained
otherwise.[FETCH]
5.4.Example
In this exampleXMLHttpRequest
,combined with concepts
defined in the sections before, and the HTMLprogress
element are used together to
display the process offetchinga resource.
<!DOCTYPE html>
< title > Waiting for Magical Unicorns</ title >
< progress id = p ></ progress >
< script >
var progressBar= document. getElementById( "p" ),
client= new XMLHttpRequest()
client. open( "GET" , "magical-unicorns" )
client. onprogress= function ( pe) {
if ( pe. lengthComputable) {
progressBar. max= pe. total
progressBar. value= pe. loaded
}
}
client. onloadend= function ( pe) {
progressBar. value= pe. loaded
}
client. send()
</ script >
Fully working code would of course be more elaborate and deal with more scenarios, such as network errors or the end user terminating the request.
Acknowledgments
Thanks to Addison Phillips, Adrian Bateman, Ahmed Kamel, Alan Thomas, Alex Hopmann, Alex Vincent, Alexey Proskuryakov, Ali Alabbas, Andrea Marchesini, Asbjørn Ulsberg, Bertrand Guay-Paquet, Björn Höhrmann, Boris Zbarsky, Caitlin Potter, Cameron McCormack, Bạch thừa hữu (Cheng-You Bai), Chris Marrin, Christophe Jolif, Charles McCathieNevile, Chirag S Kumar, Dan Winship, David Andersson, David Flanagan, David Håsäther, David Levin, Dean Jackson, Denis Sureau, Domenic Denicola, Dominik Röttsches, Doug Schepers, Douglas Livingstone, Elliott Sprehn, Elliotte Harold, Eric Lawrence, Eric Uhrhane, Erik Arvidsson, Erik Dahlström, Feras Moussa, Gideon Cohn, Glenn Adams, Gorm Haug Eriksen, Gregory Terzian, Håkon Wium Lie, Hallvord R. M. Steen, Henri Sivonen, Hiroshige Hayashizaki, Huub Schaeks, Ian Clelland, Ian Davis, Ian Hickson, Ivan Herman, Jake Archibald, Jared Jacobs, Jarred Nicholls, Jeff Walden, Jens Lindström, Jim Deegan, Jim Ley, Joe Farro, Jonas Sicking, Julian Reschke, 송정기 (Jungkee Song), Lữ khang hào (Kang-Hao Lu), Karl Dubost, Keith Yeung, Điền thôn kiện nhân (Kent TAMURA), Lachlan Hunt, Maciej Stachowiak, Magnus Kristiansen, Manish Goregaokar, Marc Hadley, Marcos Caceres, Mark Baker, Mark Birbeck, Mark Nottingham, Mark S. Miller, Martin Hassman, Mike Pennisi, Mohamed Zergaoui, Ms2ger, Noam Rosenthal, Odin Hørthe Omdal, Olli Pettay, Pawel Glowacki, Peter Michaux, Philip Jägenstedt, Philip Taylor, Rashika Jaggi, Robin Berjon, RuneF.Halvorsen, Ruud Steltenpool, Ryo Onodera, Sam Sneddon, Sergiu Dumitriu, Shivakumar Jagalur Matt, Sigbjørn Finne, Simon Pieters, Stewart Brodie, Sunava Dutta, Takeshi Kurosawa, Takeshi Yoshino, Thomas Roessler, Thomas Wisniewski, Tom Magliery, Travis Leithead, triple-underscore, Yaron Tausky, Yehuda Katz, Youenn Fablet, and Zhenbin Xu for their contributions to this standard.
Special thanks to the Microsoft employees who first implemented theXMLHttpRequest
interface, which was first widely deployed by the
Windows Internet Explorer browser.
Special thanks to Ian Hickson for drafting an initial version of this specification in the HTML Standard (then Web Applications 1.0).[HTML]
Special thanks to the W3C SVG WG for drafting the originalProgressEvent
class as part of theSVG Micro DOM.
This standard is written byAnne van Kesteren(Apple,[email protected]).
Intellectual property rights
Copyright © WHATWG (Apple, Google, Mozilla, Microsoft). This work is licensed under aCreative Commons Attribution 4.0 International License.To the extent portions of it are incorporated into source code, such portions in the source code are licensed under theBSD 3-Clause Licenseinstead.
This is the Living Standard. Those interested in the patent-review version should view theLiving Standard Review Draft.