nsIXMLHttpRequest

  • Revision slug: nsIXMLHttpRequest
  • Revision title: nsIXMLHttpRequest
  • Revision id: 59583
  • Created:
  • Creator: trevorh
  • Is current revision? No
  • Comment 7 words added, 10 words removed

Revision Content

Mozilla's XMLHttpRequest is modelled after Microsoft's IXMLHttpRequest object. The goal has been to make Mozilla's version match Microsoft's version as closely as possible, but there are bound to be some differences.

In general, Microsoft's documentation for IXMLHttpRequest can be used. Mozilla's interface definitions provide some additional documentation. The web page to look at is http://www.mozilla.org/xmlextras/.

See also XMLHttpRequest.

Mozilla's XMLHttpRequest object can be created in JavaScript like this:

  new XMLHttpRequest()

compare to Internet Explorer:

  new ActiveXObject("Msxml2.XMLHTTP")

From JavaScript, the methods and properties visible in the XMLHttpRequest object are a combination of nsIXMLHttpRequest and nsIJSXMLHttpRequest there is no need to differentiate between those interfaces.

From native code, the way to set up onload and onerror handlers is a bit different. Here is a comment from Johnny Stenback <jst@netscape.com>:

The mozilla implementation of nsIXMLHttpRequest implements the interface nsIDOMEventTarget and that's how you're supported to add event listeners. Try something like this: nsCOMPtr<nsIDOMEventTarget> target(do_QueryInterface(myxmlhttpreq)); target->AddEventListener(NS_LITERAL_STRING("load"), mylistener, PR_FALSE) where mylistener is your event listener object that implements the interface nsIDOMEventListener. The 'onload', 'onerror', and 'onreadystatechange' attributes moved to nsIJSXMLHttpRequest, but if you're coding in C++ you should avoid using those.

Though actually, if you use addEventListener from C++ weird things will happen too, since the result will depend on what JS happens to be on the stack when you do it....

Conclusion: Do not use event listeners on XMLHttpRequest from C++, unless you're aware of all the security implications. And then think twice about it.

Method Overview

void abort();
string getAllResponseHeaders();
void openRequest(in AUTF8String method, in AUTF8String url, in boolean async, in AString user, in AString password);
void open(in AUTF8String method, in AUTF8String url);
void send(in nsIVariant body);
void overrideMimeType(in AUTF8String mimetype);

Attributes

Attribute Type Description
channel nsIChannel readonly The request uses a channel in order to perform the request. This attribute represents the channel used for the request. NULL if the channel has not yet been created.

In a multipart request case, this is the initial channel, not the different parts in the multipart request.

Mozilla only. Requires elevated privileges to access.

responseXML nsIDOMDocument readonlyThe response to the request is parsed as if it were a text/xml stream. This attributes represents the response as a DOM Document object. NULL if the request is unsuccessful or has not yet been sent.
responseText AString The response to the request as text. NULL if the request is unsuccessful or has not yet been sent.
status unsigned long readonly The status of the response to the request for HTTP requests.
statusText AUTF8String readonly The string representing the status of the response for HTTP requests.
readyState long readonly The state of the request.

Possible values:

0 UNINITIALIZED open() has not been called yet.
1 LOADING send() has not been called yet.
2 LOADED send() has been called, headers and status are available.
3 INTERACTIVE Downloading, responseText holds the partial data.
4 COMPLETED Finished with all operations.
multipart boolean Set to true if the response is expected to be a stream of possibly multiple (XML) documents. If set to true, the content type of the initial response must be multipart/x-mixed-replace or an error will be triggerd. All requests must be asynchronous.

This enables server push. For each XML document that's written to this request, a new XML DOM document is created and the onload handler is called in between documents. Note that when this is set, the onload handler and other event handlers are not reset after the first XML document is loaded, and the onload handler will be called as each part of the response is received.

Methods

abort()

 void   abort();

If the request has been sent already, this method will abort the request.

getAllResponseHeaders()

 string getAllResponseHeaders();
Return value

All of the response headers as a string for HTTP requests.

Note that this will return all the headers from the *current* part of a multipart request, not from the original channel. Returns A string containing all of the response headers or NULL if the response has not yet been received.

getResponseHeader()

 ACString getResponseHeader(in AUTF8String header);
Parameters
header

The name of the header to retrieve

Return value

Returns a string containing the text of the header specified or NULL if the response has not yet been received or the header does not exist in the response.

openRequest()

  [noscript] void   openRequest(in AUTF8String method,
                                in AUTF8String url,
                                in boolean async,
                                in AString user,
                                in AString password);

Native (non-script) method to initialize a request. Note that the request is not sent until the send method is invoked. If there is an "active" request (that is, if open() or openRequest() has been called already), this is equivalent to calling abort().

Parameters
method

The HTTP method, for example "POST" or "GET". Ignored if the URL is not a HTTP(S) URL.

url

The URL to which to send the request.

async

Whether the request is synchronous or asynchronous i.e. whether send returns only after the response is received or if it returns immediately after sending the request. In the latter case, notification of completion is sent through the event listeners. This argument must be true if the multipart attribute has been set to true, or an exception will be thrown.

user

A username for authentication if necessary.

password

A password for authentication if necessary.

open()

 void   open(in AUTF8String method, in AUTF8String url);
 void   open(in AUTF8String method, in AUTF8String url, in boolean async, in AString user, in AString password);

Meant to be a script-only method for initializing a request. The parameters are similar to the ones detailed in the description of openRequest, but the last 3 are optional.

If there is an "active" request (that is, if open() or openRequest() has been called already), this is equivalent to calling abort().

Parameters
method

The HTTP method - either "POST" or "GET". Ignored if the URL is not a HTTP URL.

url

The URL to which to send the request.

async

(optional) Whether the request is synchronous or asynchronous i.e. whether send returns only after the response is received or if it returns immediately after sending the request. In the latter case, notification of completion is sent through the event listeners. The default value is true. This argument must be true if the multipart attribute has been set to true, or an exception will be thrown.

user

(optional) A username for authentication if necessary. The default value is the empty string

password

(optional) A password for authentication if necessary. The default value is the empty string

send()

 void   send(in nsIVariant body);

Sends the request. If the request is asynchronous, returns immediately after sending the request. If it is synchronous returns only after the response has been received.

All event listeners must be set before calling send().

After the initial response, all event listeners will be cleared.

Parameters
body

Either an instance of nsIDOMDocument, nsIInputStream or a string (nsISupportsString in the native calling case). This is used to populate the body of the HTTP request if the HTTP request method is "POST". If the parameter is a nsIDOMDocument, it is serialized. If the parameter is a nsIInputStream, then it must be compatible with nsIUploadChannel.setUploadStream, and a Content-Length header will be added to the HTTP request with a value given by nsIInputStream.available. Any headers included at the top of the stream will be treated as part of the message body. The MIME type of the stream should be specified by setting the Content- Type header via the setRequestHeader method before calling send.

{{ Note("When sending a nsIDOMDocument, 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.") }}

{{ method_gecko_minversion("sendAsBinary","3") }}

 void sendAsBinary(in DOMString body);

Sends the request, with the given string in binary. The string is converted to 8-bit by truncation (i.e. the high-order byte of each character is discarded).

setRequestHeader()

 void   setRequestHeader(in AUTF8String header, in AUTF8String value);

Sets a HTTP request header for HTTP requests. You must call open before setting the request headers.

Parameters
header

The name of the header to set in the request.

value

The body of the header.

overrideMimeType()

 void   overrideMimeType(in AUTF8String mimetype);

Override the mime type returned by the server (if any). 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 must be done before the send method is invoked.

Parameters

mimetype - The type used to override that returned by the server (if any).

Example code

This is a simple example code for opening a simple HTTPRequest from a xul application (like a mozilla extension) without using observers:

 var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance();
 req.open('POST', "http://www.foo.bar:8080/nietzsche.do", true);
 req.send('your=data&and=more&stuff=here');


page created by Sebastián (Cancerbero) Gurin sgurin@(nospam)montevideo.com.uy

{{ languages( { "pl": "pl/NsIXMLHttpRequest" } ) }}

Revision Source

<p>Mozilla's XMLHttpRequest is modelled after Microsoft's IXMLHttpRequest object. The goal has been to make Mozilla's version match Microsoft's version as closely as possible, but there are bound to be some differences.</p>
<p>In general, Microsoft's documentation for IXMLHttpRequest can be used. Mozilla's interface definitions provide some additional documentation. The web page to look at is <a class=" external" href="http://www.mozilla.org/xmlextras/" rel="freelink">http://www.mozilla.org/xmlextras/</a>.</p>
<p>See also <a href="/en/XMLHttpRequest" title="en/XMLHttpRequest">XMLHttpRequest</a>.</p>
<p>Mozilla's XMLHttpRequest object can be created in JavaScript like this:</p>
<pre class="eval">  new XMLHttpRequest()
</pre>
<p>compare to Internet Explorer:</p>
<pre class="eval">  new ActiveXObject("Msxml2.XMLHTTP")
</pre>
<p>From JavaScript, the methods and properties visible in the XMLHttpRequest object are a combination of nsIXMLHttpRequest and <a href="/en/nsIJSXMLHttpRequest" title="en/nsIJSXMLHttpRequest">nsIJSXMLHttpRequest</a> there is no need to differentiate between those interfaces.</p>
<p>From native code, the way to set up onload and onerror handlers is a bit different. Here is a comment from Johnny Stenback &lt;<a class=" link-mailto" href="mailto:jst@netscape.com" rel="freelink">jst@netscape.com</a>&gt;:</p>
<blockquote>The mozilla implementation of nsIXMLHttpRequest implements the interface nsIDOMEventTarget and that's how you're supported to add event listeners. Try something like this: nsCOMPtr&lt;nsIDOMEventTarget&gt; target(do_QueryInterface(myxmlhttpreq)); target-&gt;AddEventListener(NS_LITERAL_STRING("load"), mylistener, PR_FALSE) where mylistener is your event listener object that implements the interface nsIDOMEventListener. The 'onload', 'onerror', and 'onreadystatechange' attributes moved to nsIJSXMLHttpRequest, but if you're coding in C++ you should avoid using those.</blockquote>
<p>Though actually, if you use addEventListener from C++ weird things will happen too, since the result will depend on what JS happens to be on the stack when you do it....</p>
<p>Conclusion: Do not use event listeners on XMLHttpRequest from C++, unless you're aware of all the security implications. And then think twice about it.</p>
<h2 name="Method_Overview">Method Overview</h2>
<table class="standard-table"> <tbody> <tr> <td><code>void <a href="#abort()">abort</a>();</code></td> </tr> <tr> <td><code>string <a href="#getAllResponseHeaders()">getAllResponseHeaders</a>();</code></td> </tr> <tr> <td><code>void <a href="#openRequest()">openRequest</a>(in AUTF8String method, in AUTF8String url, in boolean async, in AString user, in AString password);</code></td> </tr> <tr> <td><code>void <a href="#open()">open</a>(in AUTF8String method, in AUTF8String url);</code></td> </tr> <tr> <td><code>void <a href="#send()">send</a>(in nsIVariant body);</code></td> </tr> <tr> <td><code>void <a href="#overrideMimeType()">overrideMimeType</a>(in AUTF8String mimetype);</code></td> </tr> </tbody>
</table>
<h2 name="Attributes">Attributes</h2>
<table class="standard-table"> <tbody> <tr> <td class="header">Attribute</td> <td class="header">Type</td> <td class="header">Description</td> </tr> <tr> <td><code>channel</code></td> <td><code>nsIChannel</code></td> <td><strong>readonly</strong> The request uses a channel in order to perform the request. This attribute represents the channel used for the request. NULL if the channel has not yet been created. <p>In a multipart request case, this is the initial channel, not the different parts in the multipart request.</p> <p>Mozilla only. Requires elevated privileges to access.</p> </td> </tr> <tr> <td><code>responseXML</code></td> <td><code>nsIDOMDocument</code></td> <td><strong>readonly</strong>The response to the request is parsed as if it were a text/xml stream. This attributes represents the response as a DOM Document object. NULL if the request is unsuccessful or has not yet been sent.</td> </tr> <tr> <td><code>responseText</code></td> <td><code><a href="/en/AString" title="en/AString">AString</a></code></td> <td>The response to the request as text. NULL if the request is unsuccessful or has not yet been sent.</td> </tr> <tr> <td><code>status</code></td> <td><code>unsigned long</code></td> <td><strong>readonly</strong> The status of the response to the request for HTTP requests.</td> </tr> <tr> <td><code>statusText</code></td> <td><code>AUTF8String</code></td> <td><strong>readonly</strong> The string representing the status of the response for HTTP requests.</td> </tr> <tr> <td><code>readyState</code></td> <td><code>long</code></td> <td><strong>readonly</strong> The state of the request. <p>Possible values:</p> <blockquote> 0 UNINITIALIZED open() has not been called yet.<br> 1 LOADING send() has not been called yet.<br> 2 LOADED send() has been called, headers and status are available.<br> 3 INTERACTIVE Downloading, responseText holds the partial data.<br> 4 COMPLETED Finished with all operations.</blockquote></td> </tr> <tr> <td><code>multipart</code></td> <td><code>boolean</code></td> <td>Set to true if the response is expected to be a stream of possibly multiple (XML) documents. If set to true, the content type of the initial response must be multipart/x-mixed-replace or an error will be triggerd. All requests must be asynchronous. <p>This enables server push. For each XML document that's written to this request, a new XML DOM document is created and the onload handler is called in between documents. Note that when this is set, the onload handler and other event handlers are not reset after the first XML document is loaded, and the onload handler will be called as each part of the response is received.</p> </td> </tr> </tbody>
</table>
<h2 name="Methods">Methods</h2>
<h3 name="abort()">abort()</h3>
<pre class="eval"> void   abort();
</pre>
<p>If the request has been sent already, this method will abort the request.</p>
<h3 name="getAllResponseHeaders()">getAllResponseHeaders()</h3>
<pre class="eval"> string getAllResponseHeaders();
</pre>
<h6 name="Return_value">Return value</h6>
<p>All of the response headers as a string for HTTP requests.</p>
<p>Note that this will return all the headers from the *current* part of a multipart request, not from the original channel. <code>Returns</code> A string containing all of the response headers or NULL if the response has not yet been received.</p>
<h3 name="getResponseHeader()">getResponseHeader()</h3>
<pre class="eval"> ACString getResponseHeader(in AUTF8String header);
</pre>
<h6 name="Parameters">Parameters</h6>
<dl> <dt><code>header</code></dt>
</dl>
<p>The name of the header to retrieve</p>
<h6 name="Return_value_2">Return value</h6>
<p>Returns a string containing the text of the header specified or NULL if the response has not yet been received or the header does not exist in the response.</p>
<h3 name="openRequest()">openRequest()</h3>
<pre class="eval">  [noscript] void   openRequest(in AUTF8String method,
                                in AUTF8String url,
                                in boolean async,
                                in AString user,
                                in AString password);
</pre>
<p>Native (non-script) method to initialize a request. Note that the request is not sent until the <code>send</code> method is invoked. If there is an "active" request (that is, if open() or openRequest() has been called already), this is equivalent to calling abort().</p>
<h6 name="Parameters_2">Parameters</h6>
<dl> <dt><code>method</code></dt>
</dl>
<p>The HTTP method, for example "POST" or "GET". Ignored if the URL is not a HTTP(S) URL.</p>
<dl> <dt><code>url</code></dt>
</dl>
<p>The URL to which to send the request.</p>
<dl> <dt><code>async</code></dt>
</dl>
<p>Whether the request is synchronous or asynchronous i.e. whether send returns only after the response is received or if it returns immediately after sending the request. In the latter case, notification of completion is sent through the event listeners. This argument must be true if the multipart attribute has been set to true, or an exception will be thrown.</p>
<dl> <dt><code>user</code></dt>
</dl>
<p>A username for authentication if necessary.</p>
<dl> <dt><code>password</code></dt>
</dl>
<p>A password for authentication if necessary.</p>
<h3 name="open()">open()</h3>
<pre class="eval"> void   open(in AUTF8String method, in AUTF8String url);
 void   open(in AUTF8String method, in AUTF8String url, in boolean async, in AString user, in AString password);
</pre>
<p>Meant to be a script-only method for initializing a request. The parameters are similar to the ones detailed in the description of <code>openRequest</code>, but the last 3 are optional.</p>
<p>If there is an "active" request (that is, if <code>open()</code> or <code>openRequest()</code> has been called already), this is equivalent to calling <code>abort()</code>.</p>
<h6 name="Parameters_3">Parameters</h6>
<dl> <dt><code>method</code></dt>
</dl>
<p>The HTTP method - either "POST" or "GET". Ignored if the URL is not a HTTP URL.</p>
<dl> <dt><code>url</code></dt>
</dl>
<p>The URL to which to send the request.</p>
<dl> <dt><code>async</code></dt>
</dl>
<p>(optional) Whether the request is synchronous or asynchronous i.e. whether send returns only after the response is received or if it returns immediately after sending the request. In the latter case, notification of completion is sent through the event listeners. The default value is true. This argument must be true if the multipart attribute has been set to true, or an exception will be thrown.</p>
<dl> <dt><code>user</code></dt>
</dl>
<p>(optional) A username for authentication if necessary. The default value is the empty string</p>
<dl> <dt><code>password</code></dt>
</dl>
<p>(optional) A password for authentication if necessary. The default value is the empty string</p>
<h3 name="send()">send()</h3>
<pre class="eval"> void   send(in nsIVariant body);
</pre>
<p>Sends the request. If the request is asynchronous, returns immediately after sending the request. If it is synchronous returns only after the response has been received.</p>
<p>All event listeners must be set before calling send().</p>
<p>After the initial response, all event listeners will be cleared.</p>
<h6 name="Parameters_4">Parameters</h6>
<dl> <dt><code>body</code></dt>
</dl>
<p>Either an instance of nsIDOMDocument, nsIInputStream or a string (nsISupportsString in the native calling case). This is used to populate the body of the HTTP request if the HTTP request method is "POST". If the parameter is a nsIDOMDocument, it is serialized. If the parameter is a nsIInputStream, then it must be compatible with nsIUploadChannel.setUploadStream, and a Content-Length header will be added to the HTTP request with a value given by nsIInputStream.available. Any headers included at the top of the stream will be treated as part of the message body. The MIME type of the stream should be specified by setting the Content- Type header via the setRequestHeader method before calling send.</p>
<p>{{ Note("When sending a nsIDOMDocument, versions of Firefox prior to version 3 always send the request using UTF-8 encoding; <a href='\"en/Firefox_3\"'>Firefox 3</a> properly sends the document using the encoding specified by <code>body.xmlEncoding</code>, or UTF-8 if no encoding is specified.") }}</p>
<p>{{ method_gecko_minversion("sendAsBinary","3") }}</p>
<pre class="eval"> void sendAsBinary(in DOMString body);
</pre>
<p>Sends the request, with the given string in binary. The string is converted to 8-bit by truncation (i.e. the high-order byte of each character is discarded).</p>
<h3 name="setRequestHeader()">setRequestHeader()</h3>
<pre class="eval"> void   setRequestHeader(in AUTF8String header, in AUTF8String value);
</pre>
<p>Sets a HTTP request header for HTTP requests. You must call open before setting the request headers.</p>
<h6 name="Parameters_5">Parameters</h6>
<dl> <dt><code>header</code></dt>
</dl>
<p>The name of the header to set in the request.</p>
<dl> <dt><code>value</code></dt>
</dl>
<p>The body of the header.</p>
<h3 name="overrideMimeType()">overrideMimeType()</h3>
<pre class="eval"> void   overrideMimeType(in AUTF8String mimetype);
</pre>
<p>Override the mime type returned by the server (if any). 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 must be done before the <code>send</code> method is invoked.</p>
<h6 name="Parameters_6">Parameters</h6>
<p><code>mimetype</code> - The type used to override that returned by the server (if any).</p>
<h2 name="Example_code">Example code</h2>
<p>This is a simple example code for opening a simple HTTPRequest from a xul application (like a mozilla extension) without using observers:</p>
<pre class="eval"> var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance();
 req.open('POST', "<a class=" external" href="http://www.foo.bar:8080/nietzsche.do" rel="freelink">http://www.foo.bar:8080/nietzsche.do</a>", true);
 req.send('your=data&amp;and=more&amp;stuff=here');
</pre>
<p><br>
<span class="comment">page created by Sebastián (Cancerbero) Gurin <a class=" link-mailto" href="mailto:sgurin@(nospam)montevideo.com.uy" rel="freelink">sgurin@(nospam)montevideo.com.uy</a></span></p>
<p>{{ languages( { "pl": "pl/NsIXMLHttpRequest" } ) }}</p>
Revert to this revision