AJAX - The Complete Reference

(avery) #1

PART II


Chapter 6: Networking Considerations 239


In this particular case, a JavaScript error is thrown because an attempt to parse the content
as XML is made when the content clearly is not well-formed markup. We introduce a simple
addition to the options for the request, responseContentType, which should be set to a
string containing the MIME type of what is expected as the response. If the actual content type
returned does not match this value, the handler associated with onFail will be called.
Making sure that a returned MIME type matches what is expected adds only the slightest
form of error correction. For example, if you are expecting XML, it is possible you might
receive XML that is malformed, such as a closing tag missing. If you indicate you are looking
for XML for your response, the library will invoke onFail if the response does not come back
well formed. However, if it is well formed but still in error, it is up to the programmer to check
if the returned content is in the format you expect. Unfortunately, as discussed in Chapter 4,
the ability to validate XML against a DTD is a bit limited, but it is possible to perform some
simple checks like looking to make sure that the response contains a few expected tags.
For example, in this code fragment, the response is examined to see if there is at least one
<requestip> element in the response. If there is, the content is used, if not an error is thrown.

if (response.xhr.responseXML.getElementsByTagName("requestip").length > 0)
{

FIGURE 6-4 Beware of content errors
Free download pdf