XMLHttpRequest: Difference between revisions

From MozillaZine Knowledge Base
Jump to navigationJump to search
(Attaching context info for multiple async calls)
(moved to MDC. kthxbye.)
 
Line 1: Line 1:
{{extdev}}
See [http://developer.mozilla.org/en/docs/XMLHttpRequest XMLHttpRequest] at the Mozilla Developer Center.


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.
[[Category:Redirects]]
 
==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.
 
===Example===
<pre>
req = new XMLHttpRequest();
req.open('GET', 'http://www.mozilla.org/', false);
req.send(null);
if(req.status == 200)
  dump(req.responseText);
</pre>
 
Note that this example works synchronously, so it will block the user interface if you call this from your javascript.  You should not use this in practice.
 
==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.
 
===Example===
<pre>
req = new XMLHttpRequest();
req.open('GET', 'http://www.mozilla.org/', true);
req.onreadystatechange = function () {
  if (req.readyState == 4) {
    if(req.status == 200)
      dump(req.responseText);
    else
      dump("Error loading page\n");
  }
};
req.send(null);
</pre>
 
==Multiple asynchronous calls==
If you want to fire several asynchronous calls, be carefull that that the response may not arrive in the same order (due to transfer latency). To handle correctly such cases, you have to mark your transactions to recognize them. To do that, you can attach any "user" property to the XMLHttpRequest object. You should also create a new XMLHttpRequest for each transaction.
 
Then, use the onload() event instead of the onreadystatechange(). This property is a real "event" listener. An "event" object is passed to this callback function with the "target" property pointing to the XMLHttpRequest. Then, you can get  back the custom object you attached to it.
 
===Example===
<pre>
for(var i=0; i<10; i++) {
 
var req = new XMLHttpRequest();
// Init request
req.open('GET', 'http://www.mozilla.org/', true);
 
// Attach custom data
req.myData = "request nb : " + i;
 
req.onload = function(event) {
  // The current request object object
  var self = event.target;
  dump(self.myData + "\n");
  dump(self.responseText);
}
req.send(null);
};
</pre>
 
 
==Other Properties and Methods==
In addition to the properties and methods shown above, there are other useful properties and methods on the request object.
 
===responseXML and overrideMimeType()===
If you load an XML document, the <code>responseXML</code> property will contain the document as an [http://xulplanet.com/references/objref/XMLDocument.html XMLDocument] object that you can manipulate using DOM methods. For loaded non-XML documents (whose Content-Type header does not indicate XML content), the <code>responseXML</code> property is <code>null</code>. If you know in advance that the document is valid XML, you can remedy and override a broken Content-Type header, by invoking <code>overrideMimeType('text/xml')</code> (perhaps tucking on <code>'; charset=iso-8859-1'</code> or similar, as needed) before the <code>send()</code> call.
var req = new XMLHttpRequest();
<nowiki>req.open('GET', 'http://www.example.com/really-xml.txt', false);</nowiki>
'''req.overrideMimeType('text/xml');'''
req.send(null);
alert(req.responseXML);
 
===setRequestHeader()===
This method can be used to set an HTTP header on the request before you send it.
<pre>
req = new XMLHttpRequest();
req.open('GET', 'http://www.mozilla.org/', true);
req.setRequestHeader("X-Foo", "Bar");
req.send(null);
</pre>
 
===getResponseHeader()===
This method can be used to get an HTTP header from the server response.
<pre>
req = new XMLHttpRequest();
req.open('GET', 'http://www.mozilla.org/', true);
req.send(null);
dump("Content-Type: " + req.getResponseHeader("Content-Type") + "\n");
</pre>
 
==References==
# [http://www.xulplanet.com/references/objref/XMLHttpRequest.html XULPlanet documentation]
# [http://msdn.microsoft.com/library/default.asp?url=/library/en-us/xmlsdk/html/xmobjxmlhttprequest.asp  Microsoft documentation]
# [http://jibbering.com/2002/4/httprequest.html "Using the XMLHttpRequest Object" (jibbering.com)]
# [https://sourceforge.net/projects/sarissa/ Sarissa]: Sarissa is a cross-browser ECMAScript library for client side XML manipulation, including loading XML from URLs or strings, performing XSLT transformations, XPath queries and more. Supported: Gecko (Mozilla, Firefox etc), IE, KHTML (Konqueror, Safari). If you're writing JavaScript that is used in both XUL applications and HTML pages, and the HTML pages may be viewed in non-Gecko-based applications (such as Internet Explorer, Opera, Konqueror, Safari), you should consider using Sarissa to parse and/or serialize XML. ''Note:'' Do not create a DOM object using <code>document.implementation.createDocument()</code> and then use Sarissa classes and methods to manipulate that object. It will not work. You must use Sarissa to create the initial DOM object.
 
[[Category:Example code]] [[Category:XML in JavaScript]] [[Category:Development]]

Latest revision as of 21:12, 26 September 2006

See XMLHttpRequest at the Mozilla Developer Center.