AJAX - The Complete Reference

(avery) #1

Chapter 4: Data Formats 173


PART I


File Responses

It is not possible to handle file downloads in Ajax, but since we are really talking about data
formats in general, we will quickly address this frequently asked question, “How do you
make an object download instead of display in a browser window?” It turns out you have
seen the header that makes this work earlier: Content-Disposition. If you set this header
to a value of attachment and specify a filename for the download to populate into the
browser’s “Save As” box, you are ready to go.

Content-disposition: attachment; filename=resume.doc

To set the header, you will have to either configure particular files on the Web server to
attach this header, or if the files are generated or fetched programmatically, do so in code.
While not directly related to Ajax, it’s certainly a bit of related arcane knowledge that might
help in any complex Web application you might build that deals with file uploads and
downloads.

Summary


While the choice of request and response data format is open to the discretion of the
application developer, some formats are easier to deal with than others. For transmission,
there is rarely a case where the tried and true x-www-form-urlencoded encoding of name-
value pairs will not be employed. On the response, the story is a bit different. If you are
going to load a response directly in a page, a simple markup fragment might be a good
solution. If you plan on doing more processing in JavaScript, a raw JavaScript or JSON
payload might make sense. While part of the idea of Ajax, XML can be quite onerous to deal
with because of certain limitations using DOM methods and numerous cross-browser
concerns. However, if you can mitigate some of the cross-browser issues with a library, you
will find the format quite powerful particularly when using XPath and XSL transformations.
Finally, given the text focus of XHRs, binary data is not as of yet easily supported in Ajax
applications unless you encode it into a text format.
Free download pdf