Reading response headers

This is a demo for the getAllResponseHeaders() and getResponseHeader("header") methods of the XMLHttpRequest object. This method returns all headers separated by the "newline" characters (JavaScript code '\n'). The header/value pairs are separated by the ':' character. This information can be used for processing. In this demo we obtain the headers of document employees.xml by using the HEAD method instead of GET and POST. This way the server only sends the headers without any other contents, which speeds up the processing.

xmlHttp.open("HEAD", "employees.xml");

Click the first button to get a raw header string. Click the second button to process the headers and display them in a table. Click the last button to get a specific header.

Getting all headers with getAllResponseHeaders()

The above string is obtained by the following line of code:

headersStr = xmlHttp.getAllResponseHeaders();

Processing of this string to be displayed in a table is done by the following code:

var headers = headersStr.split(/\n/);
var s = "<table border='1' cellpadding='5'>" +
   "<tr><th>Header</th> <th>Value</th></tr>";
for (var i=0; i<headers.length; i++)
  if (headers[i].length > 0)
  {
    var header = headers[i].substring(0,headers[i].indexOf(":"));
    var value = headers[i].substring(headers[i].indexOf(":")+1,
      headers[i].length);
    s += "<tr class='yello'><td>" + header +
      "</td><td>" + value + "</td></tr>";
  }
s += "</table>";
var div = document.getElementById("headers2");
div.innerHTML = s;

Getting specific headers with getResponseHeader()