180 Part II: Applied Ajax^
To access these values, use with the prefix like so: AjaxTCR.comm.LOADING. Other values,
such as the default MIME types used in requests, make good “constants” to improve
readability and to allow developers to easily change to another value.
/* Default Request Content Type */
DEFAULT_CONTENT_TYPE : "application/x-www-form-urlencoded",
NNOT EOTE JavaScript doesn’t have true constants; these are, in effect, variables. The casing is used to
indicate that they should be treated by developers as constant values.
Looking at some of the values in the library, you see the underscore ( _ ) prefix. The idea
here is to stress that these are to be treated as private values not to be modified lightly. For
example, there are a number of numeric values in an array called _networkErrorStatus.
These values correspond to values for the XHR’s status property. Some of them are familiar
HTTP status codes such as 408 (Request Timeout) or 504 (Gateway Timeout), while the others
are the various Microsoft-specific status codes like 12002 (ERROR_INTERNET_TIMEOUT).
/* the statuses for possible network errors */
/* Note 5507 = library error flag */
_networkErrorStatus : new Array(0, 408, 504, 3507, 12002, 12007, 12029,
12030, 12031, 12152),
The use of 0 and the status code 3507 should be noted here. Many browsers will put the
status to 0, particularly in error cases. Even simply trying to access the response and status
can throw an error sometimes, so there is a special status flag of 3507 that is set to indicate
such a case. You might wonder why we chose the value 3507. If you remember games of
spelling things with a calculator, you might see that the value spells a word that hints at the
success/failure of our request.
The first method in AjaxTCR.comm is _createXHR, which should look really familiar to
readers.
_createXHR : function() {
try { return new XMLHttpRequest(); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
return null;
}
This method is private so as to allow the developer to ignore the creation of the XHR
itself. Eventually, when discussing application architecture in Chapter 9, we will address
what it would take to add in the Chapter 2 communication methods as a fallback here. For
now, rather than having users create the XHR directly, they will invoke our public
sendRequest() method and pass it a URL string as a destination and an object containing
the various communication options that they would like to set.
AjaxTCR.comm.sendRequest(url,options);