--- title: XMLHttpRequest slug: Web/API/XMLHttpRequest tags: - AJAX - XMLHttpRequest translation_of: Web/API/XMLHttpRequest ---
XMLHttpRequest
is een JavaScript object dat is ontwikkeld door Microsoft en aangepast is door Mozilla, Apple, en Google. Het wordt nu gestandaardiseerd in het W3C. Het zorgt voor een makkelijke manier om informatie uit een URL op te halen zonder de gehele pagina te herladen. Een webpagina kan een gedeelte van de pagina bijwerken zonder dat de gebruiker er last van heeft. XMLHttpRequest word veel gebruikt in AJAX programering. Ondanks de naam kan XMLHttpRequest
gebruikt worden om elke soort data op te halen, dus niet alleen XML, en ondersteunt protocollen anders dan HTTP (onder andere file en ftp).
Om een instantie van XMLHttpRequest
aan te maken schrijft men simpelweg:
var myRequest = new XMLHttpRequest();
Voor meer informatie over het gebruik van XMLHttpRequest
, zie Using XMLHttpRequest.
XMLHttpRequest(JSObject objParameters); |
void abort(); |
DOMString getAllResponseHeaders(); |
DOMString? getResponseHeader(DOMString header); |
void open(DOMString method, DOMString url, optional boolean async, optional DOMString? user, optional DOMString? password); |
void overrideMimeType(DOMString mime); |
void send(); void send(ArrayBuffer data); void send(ArrayBufferView data); void send(Blob data); void send(Document data); void send(DOMString? data); void send(FormData data); |
void setRequestHeader(DOMString header, DOMString value); |
Niet-standaard methods |
---|
[noscript] void init(in nsIPrincipal principal, in nsIScriptContext scriptContext, in nsPIDOMWindow ownerWindow); |
[noscript] void openRequest(in AUTF8String method, in AUTF8String url, in boolean async, in AString user, in AString password); |
void sendAsBinary(in DOMString body); |
Attribuut | Type | Omschrijving | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
Function? |
A JavaScript function object that is called whenever the Warning: This should not be used with synchronous requests and must not be used from native code.
|
||||||||||||||||||||
readyState |
unsigned short |
The state of the request:
|
||||||||||||||||||||
response |
varies |
The response entity body according to |
||||||||||||||||||||
responseText {{ReadOnlyInline()}} |
DOMString |
The response to the request as text, or null if the request was unsuccessful or has not yet been sent. |
||||||||||||||||||||
responseType |
XMLHttpRequestResponseType |
Can be set to change the response type.
Note: Starting with Gecko 11.0, as well as WebKit build 528, these browsers no longer let you use the
responseType attribute when performing synchronous requests. Attempting to do so throws an NS_ERROR_DOM_INVALID_ACCESS_ERR exception. This change has been proposed to the W3C for standardization. |
||||||||||||||||||||
responseXML {{ReadOnlyInline()}} |
Document? |
The response to the request as a DOM Note: If the server doesn't apply the
text/xml Content-Type header, you can use overrideMimeType() to force XMLHttpRequest to parse it as XML anyway. |
||||||||||||||||||||
status {{ReadOnlyInline()}} |
unsigned short |
The status of the response to the request. This is the HTTP result code (for example, status is 200 for a successful request). |
||||||||||||||||||||
statusText {{ReadOnlyInline()}} |
DOMString |
The response string returned by the HTTP server. Unlike status , this includes the entire text of the response message ("200 OK ", for example). |
||||||||||||||||||||
timeout |
unsigned long |
The number of milliseconds a request can take before automatically being terminated. A value of 0 (which is the default) means there is no timeout. Note: You may not use a timeout for synchronous requests with an owning window.
|
||||||||||||||||||||
ontimeout |
Function |
A JavaScript function object that is called whenever the request times out. |
||||||||||||||||||||
upload |
XMLHttpRequestUpload |
The upload process can be tracked by adding an event listener to upload . |
||||||||||||||||||||
withCredentials |
boolean |
Indicates whether or not cross-site Note: This never affects same-site requests.
Note: Starting with Gecko 11.0, Gecko no longer lets you use the
withCredentials attribute when performing synchronous requests. Attempting to do so throws an NS_ERROR_DOM_INVALID_ACCESS_ERR exception. |
Attribute | Type | Description |
---|---|---|
channel {{ReadOnlyInline()}} |
{{Interface("nsIChannel")}} | The channel used by the object when performing the request. This is null if the channel hasn't been created yet. In the case of a multi-part request, this is the initial channel, not the different parts in the multi-part request. Requires elevated privileges to access. |
mozAnon {{ReadOnlyInline()}} |
boolean |
If true, the request will be sent without cookie and authentication headers. |
mozSystem {{ReadOnlyInline()}} |
boolean |
If true, the same origin policy will not be enforced on the request. |
mozBackgroundRequest |
boolean |
Indicates whether or not the object represents a background service request. If In cases in which a security dialog (such as authentication or a bad certificate notification) would normally be shown, the request simply fails instead. Note: This property must be set before calling
open() . |
mozResponseArrayBuffer {{ obsolete_inline("6") }} {{ReadOnlyInline()}} |
ArrayBuffer |
The response to the request, as a JavaScript typed array. This is NULL if the request was not successful, or if it hasn't been sent yet. |
multipart {{ obsolete_inline("22") }} |
boolean |
This Gecko-only feature was removed in Firefox/Gecko 22. Please use Server-Sent Events, Web Sockets, or Indicates whether or not the response is expected to be a stream of possibly multiple XML documents. If set to This enables support for server push; for each XML document that's written to this request, a new XML DOM document is created and the Note: When this is set, the
onload handler and other event handlers are not reset after the first XMLdocument is loaded, and the onload handler is called after each part of the response is received. |
The constructor initiates an XMLHttpRequest. It must be called before any other method calls.
Gecko/Firefox 16 adds a non-standard parameter to the constructor that can enable anonymous mode (see Bug 692677). Setting the mozAnon
flag to true
effectively resembles the AnonXMLHttpRequest()
constructor described in the XMLHttpRequest specification which has not been implemented in any browser yet (as of September 2012).
XMLHttpRequest ( JSObject objParameters );
objParameters
mozAnon
true
will cause the browser not to expose the origin and user credentials when fetching resources. Most important, this means that cookies will not be sent unless explicitly added using setRequestHeader.mozSystem
true
allows making cross-site connections without requiring the server to opt-in using CORS. Requires setting mozAnon: true
, i.e. this can't be combined with sending cookies or other user credentials. This only works in privileged (reviewed) apps; it does not work on arbitrary webpages loaded in Firefox.Aborts the request if it has already been sent.
DOMString getAllResponseHeaders();
Returns all the response headers as a string, or null
if no response has been received. Note: For multipart requests, this returns the headers from the current part of the request, not from the original channel.
DOMString? getResponseHeader(DOMString header);
Returns the string containing the text of the specified header, or null
if either the response has not yet been received or the header doesn't exist in the response.
Initializes a request. This method is to be used from JavaScript code; to initialize a request from native code, use openRequest()
instead.
open()
or openRequest()
has already been called) is the equivalent of calling abort()
.void open( DOMString method, DOMString url, optional boolean async, optional DOMString user, optional DOMString password );
method
url
async
true
, indicating whether or not to perform the operation asynchronously. If this value is false
, the send()
method does not return until the response is received. If true
, notification of a completed transaction is provided using event listeners. This must be true if the multipart
attribute is true
, or an exception will be thrown.
user
password
Overrides the MIME type returned by the server. This may be used, for example, to force a stream to be treated and parsed as text/xml, even if the server does not report it as such. This method must be called before send()
.
void overrideMimeType(DOMString mimetype);
Sends the request. If the request is asynchronous (which is the default), this method returns as soon as the request is sent. If the request is synchronous, this method doesn't return until the response has arrived.
send()
.XMLHttpRequest
specification any longer. Use an ArrayBufferView instead (see compatibility table for version information).void send();void send(ArrayBuffer data);void send(ArrayBufferView data); void send(Blob data); void send(Document data); void send(DOMString? data); void send(FormData data);
If the data is a Document
, it is serialized before being sent. When sending a Document, versions of Firefox prior to version 3 always send the request using UTF-8 encoding; Firefox 3 properly sends the document using the encoding specified by body.xmlEncoding
, or UTF-8 if no encoding is specified.
If it's an nsIInputStream
, it must be compatible with nsIUploadChannel
's setUploadStream()
method. In that case, a Content-Length header is added to the request, with its value obtained using nsIInputStream
's available()
method. Any headers included at the top of the stream are treated as part of the message body. The stream's MIMEtype should be specified by setting the Content-Type header using the setRequestHeader()
method prior to calling send()
.
The best way to send binary content (like in files upload) is using an ArrayBufferView or Blobs in conjuncton with the send()
method. However, if you want to send a stringifiable raw data, use the sendAsBinary()
method instead, or the StringView
Non native typed arrays superclass.
Sets the value of an HTTP request header. You must call setRequestHeader()
after open()
, but before send()
. If this method is called several times with the same header, the values are merged into one single request header.
void setRequestHeader( DOMString header, DOMString value );
header
value
Initializes the object for use from C++ code.
[noscript] void init( in nsIPrincipal principal, in nsIScriptContext scriptContext, in nsPIDOMWindow ownerWindow );
principal
null
.scriptContext
null
.ownerWindow
null
.Initializes a request. This method is to be used from native code; to initialize a request from JavaScript code, use open()
instead. See the documentation for open()
.
A variant of the send()
method that sends binary data.
void sendAsBinary( in DOMString body );
This method, used in conjunction with the readAsBinaryString
method of the FileReader
API, makes it possible to read and upload any type of file and to stringify the raw data.
body
sendAsBinary()
polyfillSince sendAsBinary()
is an experimental feature, here is a polyfill for browsers that don't support the sendAsBinary()
method but support typed arrays.
/*\ |*| |*| :: XMLHttpRequest.prototype.sendAsBinary() Polyfill :: |*| |*| https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#sendAsBinary() |*| \*/ if (!XMLHttpRequest.prototype.sendAsBinary) { XMLHttpRequest.prototype.sendAsBinary = function (sData) { var nBytes = sData.length, ui8Data = new Uint8Array(nBytes); for (var nIdx = 0; nIdx < nBytes; nIdx++) { ui8Data[nIdx] = sData.charCodeAt(nIdx) & 0xff; } /* send as ArrayBufferView...: */ this.send(ui8Data); /* ...or as ArrayBuffer (legacy)...: this.send(ui8Data.buffer); */ }; }
send()
: an ArrayBuffer
(ui8Data.buffer
– the commented code) or an ArrayBufferView
(ui8Data
, which is a typed array of 8-bit unsigned integers – uncommented code). However, on Google Chrome, when you try to send an ArrayBuffer
, the following warning message will appear: ArrayBuffer is deprecated in XMLHttpRequest.send(). Use ArrayBufferView instead.
Another possible approach to send binary data is the StringView
Non native typed arrays superclass in conjunction with the send()
method.XMLHttpRequest
connections per server to 6 (previous versions limit this to 2 per server). Some interactive web sites may keep an XMLHttpRequest
connection open, so opening multiple sessions to such sites may result in the browser hanging in such a way that the window no longer repaints and controls don't respond. This value can be changed by editing the network.http.max-persistent-connections-per-server
preference in about:config
.onreadystatechange
as a property of the XMLHttpRequest
instance is supported in all browsers.
Since then, a number of additional event handlers were implemented in various browsers (onload
, onerror
, onprogress
, etc.). These are supported in Firefox. In particular, see {{ interface("nsIXMLHttpRequestEventTarget") }} and Using XMLHttpRequest.
More recent browsers, including Firefox, also support listening to the XMLHttpRequest
events via standard addEventListener
APIs in addition to setting on*
properties to a handler function.
When using System XHR via the mozSystem
property, for example for Firefox OS apps, you need to be sure to add the systemXHR
permission into your manifest file. System XHR can be used in privileged or certified apps.
"permissions": { "systemXHR":{} }
{{ CompatibilityTable() }}
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
---|---|---|---|---|---|
Basic support (XHR1) | 1 | 1.0 | 5 (via ActiveXObject) 7 (XMLHttpRequest) |
{{ CompatVersionUnknown() }} | 1.2 |
send(ArrayBuffer) |
9 | 9 | 10 | 11.60 | {{ compatUnknown() }} |
send(ArrayBufferView) |
22 | 20 | {{ compatUnknown() }} | {{ compatUnknown() }} | {{ compatUnknown() }} |
send(Blob) |
7 | 3.6 | 10 | 12 | {{ compatUnknown() }} |
send(FormData) |
6 | 4 | 10 | 12 | {{ compatUnknown() }} |
sendAsBinary(DOMString) |
{{ compatNo() }} – use the polyfill | 1.9 | {{ CompatNo() }} | {{ CompatNo() }} | {{ CompatNo() }} |
response |
10 | 6 | 10 | 11.60 | {{ compatUnknown() }} |
responseType = 'arraybuffer' |
10 | 6 | 10 | 11.60 | {{ compatUnknown() }} |
responseType = 'blob' |
19 | 6 | 10 | 12 | {{ compatUnknown() }} |
responseType = 'document' |
18 | 11 | 10 | {{ CompatNo() }} | 6.1 |
responseType = 'json' |
{{ CompatNo() }} | 10 | {{ CompatNo() }} | 12 | {{ CompatNo() }} |
Progress Events | 7 | 3.5 | 10 | 12 | {{ compatUnknown() }} |
withCredentials |
3 | 3.5 | 10 | 12 | 4 |
timeout |
29 | 12.0 | 8 | 12 | {{ CompatNo() }} |
responseType = 'moz-blob' |
{{ CompatNo() }} | 12.0 | {{ CompatNo() }} | {{ CompatNo() }} | {{ CompatNo() }} |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Phone | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | {{ CompatUnknown() }} | 0.16 | {{ CompatVersionUnknown() }} | {{ CompatUnknown() }} | {{ CompatUnknown() }} | {{ CompatUnknown() }} |
Gecko 11.0 {{ geckoRelease("11.0") }} removed support for using the responseType
and withCredentials
attributes when performing synchronous requests. Attempting to do so throws an NS_ERROR_DOM_INVALID_ACCESS_ERR
exception. This change has been proposed to the W3C for standardization.
Gecko 12.0 {{ geckoRelease("12.0") }} and later support using XMLHttpRequest
to read from data:
URLs.
Gecko 20.0 {{ geckoRelease("20.0") }} adds the support of sending an ArrayBufferView
- sending a plain ArrayBuffer
is not part of the XMLHttpRequest
specification any longer and should be treated as deprecated.
{{ languages( { "es": "es/XMLHttpRequest", "fr": "fr/XMLHttpRequest", "it": "it/XMLHttpRequest", "ja": "ja/XMLHttpRequest", "ko": "ko/XMLHttpRequest", "pl": "pl/XMLHttpRequest", "zh-cn": "zh-cn/DOM/XMLHttpRequest" } ) }}