While writing about adding support for different status codes into the AjaxRequest object (very easy, as I'll show momentarily), I made a little test page to try each of the initial set: HTTP Status Codes. Just click each link (check Firebug) and it optionally fetches all, part, or none of a 400-line file.
Now on to the excerpt:
Most browsers and XML feed readers take full advantage of the HTTP/1.1 specification to greatly reduce the data sent from the server, and the XMLHttpRequest object gives developers access to the same functionality. Two intertwined aspects of the HTTP/1.1 specification in particular can help Ajax-driven applications: status codes and cache-control.
Supporting these in the previously defined AjaxRequest object comes easily. It already supports setting custom headers through its headers object, just like setting GET and POST variables. In order to support the various status codes that the server can return, it just takes adding event types and adding some more flexibility to the stateChanged() method by changing it from:
// Event dispatching
AjaxRequest.prototype.events = {
abort : [],
data : [],
load : [],
open : [],
send : [],
};
// Callback for this.xhr.onreadystatechanged
AjaxRequest.prototype.stateChanged = function() {
// Only trigger load if finished returning
switch(this.xhr.readyState) {
case 3:
var e = new AjaxEvent(this);
this.dispatchEvent('data', e);
break;
case 4:
// Only continue if status OK
if (this.xhr.status == 200) {
var e = new AjaxEvent(this);
this.dispatchEvent('load', e);
}
}
}
...to a new version that can handle multiple status codes:
// Event dispatching
AjaxRequest.prototype.events = {
abort : [],
data : [],
internalservererror : [],
load : [],
notfound : [],
notmodified : [],
open : [],
partialload : [],
requestedrangenotsatisfiable : [],
send : [],
unauthorized : []
};
// Simple lookup of event types by status code
AjaxRequest.prototype.statusCodeEvents = {
200 : 'load',
206 : 'partialload',
304 : 'notmodified',
401 : 'unauthorized',
404 : 'notfound',
416 : 'requestedrangenotsatisfiable',
500 : 'internalservererror'
};
// Callback for this.xhr.onreadystatechanged
AjaxRequest.prototype.stateChanged = function() {
// Only trigger load if finished returning
switch(this.xhr.readyState) {
case 3:
var e = new AjaxEvent(this);
this.dispatchEvent('data', e);
break;
case 4:
if (this.statusCodeEvents[this.xhr.status]) {
var e = new AjaxEvent(this);
this.dispatchEvent(this.statusCodeEvents[this.xhr.status], e);
}
}
}
The new implementation of stateChanged() now simply triggers the event mapped to the returned status code from the request, if the AjaxRequest object implements that event type. While the list of status codes only includes the most commonly used codes for this chapter's usage, it can include any additional codes added to the events and statusCodeEvents objects.
Labels: advanced ajax, excerpts, javascript, sample code, web standards