XMLHttpRequest
is a JavaScript object that was designed by Microsoft and adopted by Mozilla, Apple, and Google. It's now beingstandardized in the W3C. It provides an easy way to retrieve data at a URL. Despite its name, XMLHttpRequest
can be used to retrieve any type of data, not just XML, and it supports protocols other than HTTP (including file
and ftp
).
To create an instance of XMLHttpRequest
, simply do this:
var req = new XMLHttpRequest();
For details about how to use XMLHttpRequest
, see Using XMLHttpRequest.
Method overview
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(Blob data); void send(Document data); void send(DOMString? data); void send(FormData data); |
void setRequestHeader(DOMString header, DOMString value); |
Non-standard 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); |
Properties
Attribute | Type | Description | ||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Function? | A JavaScript function object that is called whenever the
Warning: This must not be used from native code. You should also not use this with synchronous requests.
| ||||||||||||||||||
readyState | unsigned short | The state of the request:
| ||||||||||||||||||
response | varies | The response entity body according to | ||||||||||||||||||
responseText | DOMString | The response to the request as text, or null if the request was unsuccessful or has not yet been sent. Read-only. | ||||||||||||||||||
responseType | XMLHttpRequestResponseType | Can be set to change the response type. This tells the server what format you want the response to be in.
| ||||||||||||||||||
responseXML | 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 | 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). Read-only. | ||||||||||||||||||
statusText | DOMString | The response string returned by the HTTP server. Unlike status , this includes the entire text of the response message ("200 OK ", for example). Read-only. | ||||||||||||||||||
upload | XMLHttpRequestUpload | The upload process can be tracked by adding an event listener to upload . | ||||||||||||||||||
withCredentials | boolean | Indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies or authorization headers. The default is
Note: This never affects same-site requests.
|
Non-standard properties
Attribute | Type | Description |
---|---|---|
channel | 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; read-only. |
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. |
mozResponseArrayBuffer Requires Gecko 2.0Obsolete since Gecko 6 | 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. Read only. |
multipart | boolean | 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.
|
Methods
abort()
Aborts the request if it has already been sent.
getAllResponseHeaders()
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.
getResponseHeader()
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.
open()
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 );
Parameters
- The HTTP method to use; either "POST" or "GET". Ignored for non-HTTP(S) URLs.
- The URL to which to send the request.
-
An optional boolean parameter, defaulting to
true
, indicating whether or not to perform the operation asynchronously. If this value isfalse
, thesend()
method does not return until the response is received. Iftrue
, notification of a completed transaction is provided using event listeners. This must be true if themultipart
attribute istrue
, or an exception will be thrown. - The optional user name to use for authentication purposes; by default, this is an empty string.
- The optional password to use for authentication purposes; by default, this is an empty string.
method
url
async
user
password
overrideMimeType()
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);
send()
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()
.
void send(); void send(ArrayBuffer data); void send(Blob data); void send(Document data); void send(DOMString? data); void send(FormData data);
Notes
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()
.
setRequestHeader()
Sets the value of an HTTP request header.You must call open()
before using this method.
void setRequestHeader( DOMString header, DOMString value );
Parameters
- The name of the header whose value is to be set.
- The value to set as the body of the header.
header
value
Non-standard methods
init()
Initializes the object for use from C++code.
[noscript] void init( in nsIPrincipal principal, in nsIScriptContext scriptContext, in nsPIDOMWindow ownerWindow );
Parameters
-
The principal to use for the request; must not be
null
. -
The script context to use for the request; must not be
null
. -
The window associated with the request; may be
null
.
principal
scriptContext
ownerWindow
openRequest()
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()
.
sendAsBinary()
A variant of the send()
method that sends binary data.
void sendAsBinary( in DOMString body );
Parameters
- The request body as a DOMstring. This data is converted to a string of single-byte characters by truncation (removing the high-order byte of each character).
body
Notes
- By default, Firefox 3 limits the number of
XMLHttpRequest
connections per server to 6 (previous versions limit this to 2 per server). Some interactive web sites may keep anXMLHttpRequest
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 thenetwork.http.max-persistent-connections-per-server
preference inabout:config
. - From Gecko 7.0 headers set by
setRequestHeader()
are sent with the request when following a redirect. Previously these headers would not be sent. XMLHttpRequest
is implemented in Gecko using thensIXMLHttpRequest
,nsIXMLHttpRequestEventTarget
, andnsIJSXMLHttpRequest
interfaces.
Events
onreadystatechange
as a property on the xhr object 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 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.
Browser compatibility
- Desktop
- Mobile
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
---|---|---|---|---|---|
Basic support (XHR1) | 1 | 1.0 | 5 (via ActiveXObject) 7 (XMLHttpRequest) | (Yes) | 1.2 |
send(ArrayBuffer) | 9 | 9 | ? | 11.60 | ? |
send(Blob) | 7 | 3.6 | ? | 12 | ? |
send(FormData) | 6 | 4 | ? | 12 | ? |
response | 10 | 6 | 10 | 11.60 | ? |
responseType = 'arraybuffer' | 10 | 6 | 10 | 11.60 | ? |
responseType = 'blob' | 19 | 6 | 10 | 12 | ? |
responseType = 'document' | 18 | 11 | -- | -- | -- |
responseType = 'json' | -- | 10 | -- | 12 | -- |
Progress Events | 7 | 3.5 | 10 | 12 | ? |
withCredentials | 3 | 3.5 | 10 | 12 | 4 |
See also
- MDN articles about XMLHttpRequest:
- XMLHttpRequest references from W3C and browser vendors:
- W3C: XMLHttpRequest (base features)
- W3C: XMLHttpRequest (latest editor's draft with extensions to the base functionality, formerly XMLHttpRequest Level 2
- Microsoft documentation
- Apple developers' reference
- "Using the XMLHttpRequest Object" (jibbering.com)
- XMLHttpRequest - REST and the Rich User Experience
- HTML5 Rocks - New Tricks in XMLHttpRequest2