XMLHttpRequest
From MDC
XMLHttpRequest is a JavaScript object that was created by Microsoft and adopted by Mozilla. You can use it to easily retrieve data via HTTP. Despite its name, it can be used for more than just XML documents. In Gecko, this object implements the nsIJSXMLHttpRequest and nsIXMLHttpRequest interfaces. Recent versions of Gecko have some changes to this object, see XMLHttpRequest changes for Gecko1.8.
Contents |
[edit] Basic Usage
Using XMLHttpRequest is very simple. You create an instance of the object, open a URL, and send the request. The HTTP status code of the result, as well as the result document are available in the request object afterwards.
data.inputEncoding.[edit] Example
var req = new XMLHttpRequest();
req.open('GET', 'http://www.mozilla.org/', true);
req.send(null);
if(req.status == 200)
dump(req.responseText);
[edit] Example with non http protocol
var req = new XMLHttpRequest();
req.open('GET', 'file:///home/user/file.json', false);
req.send(null);
if(req.status == 0)
dump(req.responseText);
status and an empty string for statusText. Refer to bug 331610 for more insight.[edit] Asynchronous Usage
If you intend to use XMLHttpRequest from an extension, you should let it load asynchronously. In asynchronous usage, you get a callback when the data has been received, which lets the browser continue to work as normal while your request is happening.
[edit] Example
var req = new XMLHttpRequest();
req.open('GET', 'http://www.mozilla.org/', true);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if(req.status == 200)
dump(req.responseText);
else
dump("Error loading page\n");
}
};
req.send(null);
[edit] Monitoring progress
XMLHttpRequest provides the ability to listen to various events that can occur while the request is being processed. This includes periodic progress notifications, error notifications, and so forth.
If, for example, you wish to provide progress information to the user while the document is being received, you can use code like this:
function onProgress(e) {
var percentComplete = (e.position / e.totalSize)*100;
...
}
function onError(e) {
alert("Error " + e.target.status + " occurred while receiving the document.");
}
function onLoad(e) {
// ...
}
// ...
var req = new XMLHttpRequest();
req.onprogress = onProgress;
req.open("GET", url, true);
req.onload = onLoad;
req.onerror = onError;
req.send(null);
The onprogress event's attributes, position and totalSize, indicate the current number of bytes received and the total number of bytes expected, respectively.
All of these events have their target attribute set to the XMLHttpRequest they correspond to.
target, currentTarget, and this fields of the event object are set to reference the correct objects when calling event handlers for XML documents represented by XMLDocument. See bug 198595 for details.[edit] Other Properties and Methods
In addition to the properties and methods shown above, there are other useful properties and methods on the request object.
[edit] responseXML
If you load an XML document, the responseXML property will contain the document as an XmlDocument object that you can manipulate using DOM methods. If the server sends well-formed XML but does not specify an XML Content-Type header, you can use overrideMimeType() to force the document to be parsed as XML. If the server does not send well-formed XML, responseXML will be null regardless of any content type override.
[edit] overrideMimeType()
This method can be used to force a document to be handled as a particular content type. You will generally want to use when you want to useresponseXML and the server sends you XML, but does not send the correct Content-Type header. send().
var req = new XMLHttpRequest();
req.open('GET', 'http://www.mozilla.org/', true);
req.overrideMimeType('text/xml');
req.send(null);
[edit] setRequestHeader()
This method can be used to set an HTTP header on the request before you send it.
open() before calling this method.
var req = new XMLHttpRequest();
req.open('GET', 'http://www.mozilla.org/', true);
req.setRequestHeader("X-Foo", "Bar");
req.send(null);
[edit] getResponseHeader()
This method can be used to get an HTTP header from the server response.
var req = new XMLHttpRequest();
req.open('GET', 'http://www.mozilla.org/', false);
req.send(null);
dump("Content-Type: " + req.getResponseHeader("Content-Type") + "\n");
[edit] mozBackgroundRequest
This property can be used to prevent authentication and bad certificate dialogs from popping up for the request. Also the request will not be canceled if the window it belongs to is closed. This property works for chrome code only. New in Firefox 3
var req = new XMLHttpRequest();
req.mozBackgroundRequest = true;
req.open('GET', 'http://www.mozilla.org/', true);
req.send(null);
[edit] Using from XPCOM components
XMLHttpRequest cannot be instantiated using the XMLHttpRequest() constructor from a JavaScript XPCOM component. The constructor is not defined inside components and the code results in an error. You'll need to create and use it using a different syntax.
Instead of this:
var req = new XMLHttpRequest();
req.onprogress = onProgress;
req.onload = onLoad;
req.onerror = onError;
req.open("GET", url, true);
req.send(null);
Do this:
var request = Components.
classes["@mozilla.org/xmlextras/xmlhttprequest;1"].
createInstance();
// QI the object to nsIDOMEventTarget to set event handlers on it:
request.QueryInterface(Components.interfaces.nsIDOMEventTarget);
request.addEventListener("progress", function(evt) { ... }, false);
request.addEventListener("load", function(evt) { ... }, false);
request.addEventListener("error", function(evt) { ... }, false);
// QI it to nsIXMLHttpRequest to open and send the request:
request.QueryInterface(Components.interfaces.nsIXMLHttpRequest);
request.open("GET", "http://www.example.com/", true);
request.send(null);
[edit] Limited Number Of Simultaneous xmlHttpRequest Connections
The about:config preference: network.http.max-persistent-connections-per-server limits the number of connections. In Firefox 3 this value is 6 by default, previous versions use 2 as the default. Some interactive web pages using xmlHttpRequest may keep a connection open. Opening two or three of these pages in different tabs or on different windows may cause the browser to hang in such a way that the window no longer repaints and browser controls don't respond.
[edit] Retrieving Binary Content
// Fetches BINARY FILES synchronously using XMLHttpRequest
function load_binary_resource(url) {
var req = new XMLHttpRequest();
req.open('GET',url,false);
//XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]
req.overrideMimeType('text/plain; charset=x-user-defined');
req.send(null);
if (req.status != 200) return '';
return req.responseText;
}
var filestream = load_binary_resource(url);
// x is the offset (i.e. position) of the byte in the returned binary file stream. The valid range for x is from 0 up to filestream.length-1.
var abyte = filestream.charCodeAt(x) & 0xff; // throw away high-order byte (f7)
See downloading binary streams with XMLHttpRequest for a detailed explanation.