Home > Articles > Programming > Java

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Working with XmlHttpRequest

If your audience primarily uses later versions of Internet Explorer or Gecko-based browsers (Mozilla, Firefox, Netscape 7), you could decide to use the XmlHttpRequest object to download additional content into your web pages. The initial step is very similar to the one described earlier. For each placeholder, you need a JavaScript function call to start the load process:

<div id="header">
  <div style="height: 100px; width: 100%"></div>

The loadContent function is radically different, however: It creates a new XmlHttpRequest object, assigns an event handler to it, and starts the asynchronous loading process:

function loadContent(id,url) {
  try {
    var rq = new XMLHttpRequest() ;
    rq.open("GET", url, true);
    rq.onreadystatechange =  function() { contentLoaded(rq,url,id) }
  } catch (err) {
    alert("cannot load "+url+" into "+id) ;

The callback function contentLoaded checks the readiness of the XmlHttpRequest object and the completion status (if the request has completed), and extracts the HTML markup from the response. The easiest way to extract the HTML code (unless you use XHTML, in which case you can use the XML DOM interface) is to use string-handling functions to find the text between the <body> and </body> tags:

function contentLoaded(rq,url,id) {
  try {
    if (rq.readyState != 4) { return; }
    if (rq.status != 200) { alert("failed to load "+url); return; }

    var txt = rq.responseText ;

// find the start of the <body> tag
    var startBodyTag = txt.indexOf("<body")

// find the end of the <body> tag, skipping any attributes
    var endOfStartTag = txt.indexOf(">",startBodyTag+1)

// find the </body> tag, copy until end of text if missing
    var endBodyTag = txt.indexOf("</body")
    if (endBodyTag == -1) { endBodyTag = txt.length ; }

// extract the actual content
    var bodyContent = txt.substring(endOfStartTag+1,endBodyTag)

    if (bodyContent) {
      var placeholder = document.getElementById(id) ;
      placeholder.innerHTML = bodyContent;
  } catch (err) {
    alert("cannot load "+url+" into "+id) ;

Compared to the IFRAME-based method described earlier, using the XmlHttpRequest object has the following benefits:

  • The code is cleaner and doesn't rely on context switches between pages.

  • The XmlHttpRequest object gives you the ability to detect and process errors through its readyState and status properties. The only indication that something went wrong with an IFRAME-loaded content is the lack of the callback call.

  • You can implement parallel load of the content elements (as shown in this section) or sequence the load requests to minimize bandwidth utilization.

  • + Share This
  • 🔖 Save To Your Account