Trainer thoughts on web design techs and tools

The readyState holds the current state of an XMLHttpRequest object. It is generally used to see if the requested content has been received. According to the W3C specification:

  • 0 = UNSENT
  • 1 = OPENED
  • 2 = HEADERS_RECEIVED
  • 3 = LOADING
  • 4 = DONE

Here is a simple script to show how to use readyState to output the responseHeaders:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
window.onload = function() {
	var ajax = new XMLHttpRequest();
	var responseHeaders;
	var output = document.getElementById("headers");
	var temp = "";
	ajax.open("GET", "arrays.html", true);
	ajax.send();
	ajax.onreadystatechange = function() {
		if ( this.readyState == 2 ) {
			responseHeaders = this.getAllResponseHeaders().split("\n");
			temp = "<ol>";
			for (var i in responseHeaders) {
				if (responseHeaders[i].trim().length > 0) {
					temp += "<li>" + responseHeaders[i] + "</li>";
				}
			}
			temp += "</ol>";
			output.innerHTML=temp;
		}
	}
}

This script works as expected in IE9, Firefox 4, Chrome 10, and Safari 5, but errors in Opera 11. Opera doesn’t appear to have the responseHeaders yet so this.getAllResponseHeaders() causes an INVALID_STATE_ERR exception.

To get around this bug, we change our if condition as follows:

if ( this.readyState > 2 && typeof responseHeaders == "undefined" ) {...

This if block will run if this.readyState is greater than 2 and the responseHeaders variable is yet to be defined. The first part of the condition will be true in readyStates 3 and 4, but the second part will only be true in readyState 3.

No TweetBacks yet. (Be the first to Tweet this post)

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

© Webucator, Inc. All rights reserved. | Toll Free: 877-932-8228 | UK: 0808-101-3484 | From outside the USA: 315-849-2724 | Fax: 315-849-2723