The first half of this article got you up to speed with the basics of working with the Dojo toolkit. You learned how to install Dojo in your Web applications, and you developed a simple Hello World program. In the process you learned first-hand how the toolkit's infrastructure for classes and modules simplifies the writing of object-oriented, well-scoped JavaScript. In this second half of the article we'll enter more advanced territory, with a look at the real-world requirements of Ajax applications. You'll then learn about the infrastructure code Dojo provides to help you handle these requirements, even in complex application scenarios.
Ajax is a foundational technology for Web 2.0 applications. Ajax applications typically have three requirements:
1. A (usually asynchronous) request to the server that gets a response without requiring the browser page to be refreshed
2. A modification to the page document -- such as a color change or the addition or removal of some content -- that indicates visually to the user that the response has occurred
3. Eventing, which allows you to attach a JavaScript function to a user- or system-initiated event -- a button click by the user, for example -- so that the function is called when the event occurs
Dojo simplifies the development of all three of these Ajax requirements and ensures that the resulting application will work in multiple browsers. It does this by providing an infrastructure for making asynchronous requests, and for using cross-browser-compatible DOM-manipulation code. In the next sections I'll introduce you to the key elements of Dojo's Ajax infrastructure and show you how to use it in Ajax development.
Making an XMLHttpRequest
Most browsers provide a XMLHttpRequest object that allows you to make an asynchronous request to the server and get a response without refreshing the whole page. But if you try to use the XMLHttpRequest object directly without using a JavaScript framework such as Dojo, you'll run into problems such as memory leaks and divergent, browser-specific APIs. The Dojo toolkit simplifies the use of XMLHttpRequest by providing a set of wrapper functions for the object. The wrapper functions address common infrastructural issues by providing a unified API, cross-browser compatibility, error handling, data encoding, and much more.
The four wrapper functions all start with xhr (a short form of XMLHttpRequest):
* xhrGet() allows you to make an HTTP GET method call to the server.
* xhrPost() allows you to make an HTTP POST method call to the server.
* xhrPut() allows you to make an HTTP PUT method call to the server.
* xhrDelete() allows you to make an HTTP DELETE method call to the server.
Dojo also provides a generic xhr() function that takes the name of the HTTP method that you want to use as an argument and makes the requested method call.