AJAX - The Complete Reference

(avery) #1

PART II


Chapter 8: User Interface Design for Ajax 343


status to users. For example, the XHR object’s readyState property can be consulted for
basic request status. If we consider that we are in readyState 2, then the request has been
sent but no data has come back. This implies that the request is trying to make it to the
server or the server is busy processing the data. Once an XHR reaches a readyState
value of 3, some data has arrived so you can assume that the download of the response is
proceeding. When the readyState value reaches 4, the request has been received and local
processing proceeds. Given this basic idea, you might consider building a request callback
that can modify the status messages more appropriately. A skeleton of such code is shown
here that leaves out all possible status responses purposefully so just the general sense of the
approach can be seen.

function handleResponse(xhr)
{
switch (xhr.readyState)
{
0: /* not sent yet */
1: break;
2: /* show request sent indication */
break;
3: /* show response being received indication */
break;
4: try {
switch (xhr.status)
{
"200":
/* handle proper response */
break;
"403":
"404": /* show or handle basic client errors */
break;
"500": /* server problem show error */
break;
"503": /* server unavailable retry
show retry indication */
break;
}
} catch(e) { /* malformed request error */ }
break;
default: /* readyState error condition */
}
}

In each invocation of the callback, the readyState should change. The cursor or the
status image can then be modified to suit the situation. For example, a different image,
cursor, or loading message might be used in the case of the request being sent, the response
Free download pdf