6.1. Using the Dojo Toolkit We'll start our look at Ajax frameworks with the Dojo Toolkit. Dojo is an open source DHTML toolkit written in JavaScript. It includes many utilities that go beyond Ajax. The libraries that we are most interested in include:
dojo.io Platform-independent input/output APIs
dojo.rpc RPC, the Dojo way
dojo.json JSON, the Dojo way Although we are only going to use the dojo.io library for this example, you should look at the Dojo manual (http://manual.dojotoolkit.org) for information on dojo.rpc and dojo.json. The other libraries that Dojo contains are:
dojo.lang Utility routines to make JavaScript easier to use
dojo.string String manipulation routines
dojo.dom DOM manipulation routines
dojo.style CSS style manipulation routines
dojo.html HTML-specific operations
dojo.event Aspect Oriented Programming-inspired event system
dojo.reflect Reflection API
dojo.date Date manipulation
dojo.logging.Logger Logging library
dojo.profile JS Profiler
dojo.regexp Regular expression generators
dojo.collections Contains Dictionary, ArrayList, Queue, SortedList, Stack, and Set sub-parts
dojo.animation.Animation Animation support
dojo.dnd Drag-and-drop support
dojo.validate Data validation methods (isText, isNumber, isValidDate, etc.)
dojo.fx Fading, exploding visual effects
dojo.graphics.Colorspace Colorspace manipulation
dojo.graphics.color Color manipulation
dojo.svg SVG library
dojo.crypto Cryptographic routines
dojo.math.Math Math library
dojo.math.curves Curve-generation library
dojo.math.matrix Linear algebra
dojo.math.points Point manipulations
dojo.storage Storage system that implements a local durable cache
dojo.xml.Parse First-pass XML to JS parser
dojo.uri URI/URL manipulation routines That's a handful. You can accomplish a lot with Dojo, and it is worth exploring further, but doing so is outside the scope of this book. Again, consult the Dojo manual for more information on the Dojo libraries. Now, back to the task at hand: using Dojo to set up an Ajax call. In the previous chapter, we used the following code to retrieve the state and city corresponding to a user-entered zip code: function retrieveCityState( ) { var zip = document.getElementById("zipcode"); var url = "/ajax-customer-lab5-1/zipcodes?zip=" + escape(zip.value); name.value="?"+name.value; if (window.XMLHttpRequest) { req = new XMLHttpRequest( ); } else if (window.ActiveXObject) { req = new ActiveXObject("Microsoft.XMLHTTP"); } req.open("Get",url,true); req.onreadystatechange = callbackCityState; req.send(null); } Most of the retrieveCityState( ) function has to do with initializing the XMLHttpRequest object. This code is fragile: if the test for XMLHttpRequest ever changes, you'll have to modify the application (and every other application you've created that uses code like this). Therefore, it makes sense to initialize XMLHttpRequest in a library function. You could create your own library, but why go to the trouble when someone's already done it for you? Here's the retrieveCityState( ) method rewritten to use Dojo: function retrieveCityState( ) { zip = document.getElementById("zipcode"); dojo.io.bind({ url: "/ch06-Frameworks/zipcodes?zip=" + escape(zip.value), load: function(type, data, evt){ displayCityAndState(data); }, error: function(type, data, evt){ reportError(type,data,evt); }, mimetype: "text/plain" }); } This revised version of retrieveCityState( ) uses the dojo.io.bind( ) function to set up the XMLHttpRequest object and the callback and error-handling functions. The parameters that are passed to dojo.io.bind( ) are:
url The URL of the Ajax service that handles the request.
load The JavaScript callback function that is called when the response arrives.
error The JavaScript function that is called in case of any errors.
mimetype The MIME type that is used to interpret the response coming back from the server. The type will almost always be text/plain. This parameter does not set an outgoing MIME header for HTTP transports. To use dojo.io.bind( ), you must first install the Dojo Toolkit. Point your browser to http://www.dojotoolkit.org and download the library. Extract the file dojo.js and put it in your web application so you can import the JavaScript library: <script language="JavaScript" src="/books/4/163/1/html/2/dojo.js"></script> That's all there is to it. To handle errors, add a reportErrors( ) function, as indicated by the error: key in the dojo.io.bind( ) call: function reportError(type,data,evt) { alert('error retrieving a city and state for that zip code.'); } That's all it takes to use the Dojo Toolkit to take care of the XMLHTTPRequest communication for you. Example 6-1 presents the revised HTML file for our Customer Sign-up page, including the JavaScript for using dojo.io.bind( ) to retrieve the city and state information. Example 6-1. The HTML and JavaScript code for dojoindex.html <html> <head> <meta name="generator" content="HTML Tidy, see www.w3.org"> <LINK REL="stylesheet" TYPE="text/css" HREF="oreillyajax.css"> <title>AJAX Customer Sign-up</title> <script language="JavaScript" src="/books/4/163/1/html/2/scripts/dojo.js"></script> <script language="JavaScript" type="text/javascript"> function retrieveCityState( ) { zip = document.getElementById("zipcode"); dojo.io.bind({ url: "/ch06-Frameworks/zipcodes?zip=" + escape(zip.value), load: function(type, data, evt){ displayCityAndState(data); }, error: function(type, data, evt){ reportError(type,data,evt); }, mimetype: "text/plain" }); } function displayCityAndState(data) { var jsonData = data; var myJSONObject = eval('(' + jsonData + ')'); if (myJSONObject.location.city== null) { alert('no entry in database for zip code: '+myJSONObject.location.zip); var city = document.getElementById('city').value=""; var city = document.getElementById('state').value=""; } else { var city = document.getElementById('city'). value=myJSONObject.location.city; var city = document.getElementById('state'). value=myJSONObject.location.state; } } function reportError(type,data,evt) { alert('error retrieving a city and state for that zip code.'); } </script> </head> <body> <h1>AJAX Zip Code Lookup with Dojo</h1> <form name="form1" action="signup" method="get"> <table align="left" > <tr> <td colspan="2"> <table > <tr> <td > <h2>Choose a username and password............</h2> </td> </tr> </table> </td> </tr> <tr> <td>User Name:</td> <td align="left"> <input type="text" name="ajax_username" autocomplete="off" onblur="validateUsername( )"> </td> </tr> <tr> <td>Password:</td> <td align="left"> <input type="password" name="password"> </td> </tr> <tr> <td>Confirm Password:</td> <td align="left"> <input type="password" name="confirmpassword"> </td> </tr> <tr> <td> </td> </tr> <tr> <td colspan="2"> <table align="left" > <tr> <td > <h2>Fill in your contact information...</h2> </td> </tr> </table> </td> </tr> <tr> <td>Email:</td> <td align="left"><input type="text" name="email"></td> </tr> <tr> <td>Name:</td> <td align="left"> <input type="text" name="customername"> </td> </tr> <tr> <td>Address:</td> <td align="left"><input type="text" name="address"></td> </tr> <tr> <td>Zip Code:</td> <td align="left"> <input type="text" name="zipcode" onblur="retrieveCityState( )"> </td> </tr> <tr> <td>City:</td> <td align="left"><input type="text" name="city"></td> </tr> <tr> <td>State:</td> <td align="left"><input type="text" name="state"></td> </tr> <tr> <td>Error:</td> <td align="left"> <input type="text" name="ziperrorstate"> </td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" value="Sign Up"> </td> </tr> <tr> <td colspan="2" align="center"> <a href="manager.html">Customer Manager</a> </td> </tr> </table> </form> </body> </html> | As browsers evolve, and as JavaScript itself evolves, the toolkits will evolve, too. Libraries such as Dojo let you take advantage of improvements made to browsers and to JavaScript without rewriting your existing code. These libraries insulate you from changes while at the same time enabling you to take advantage of the advances in technology. |