With its rich grouping of technologies, Ajax developers can create interactive web applications with XML-based web services, using JavaScript in the browser to process the web server res
Trang 1By Bruce W Perry
Publisher: O'Reilly Pub Date: March 2006 Print ISBN-10: 0-596-10169-4 Print ISBN-13: 978-0-59-610169-5 Pages: 438
Table of Contents | Index
Ajax, the popular term for Asynchronous JavaScript and XML, is one of the most important combinations of technologies for web developers to know these days With its rich
grouping of technologies, Ajax developers can create interactive web applications with XML-based web services, using JavaScript in the browser to process the web server
response.
Taking complete advantage of Ajax, however, requires something more than your typical
"how-to" book What it calls for is Ajax Hacks from O'Reilly This valuable guide provides
direct, hands-on solutions that take the mystery out of Ajax's many capabilities Each hack represents a clever way to accomplish a specific task, saving you countless hours of
searching for the right answer.
A smart collection of 100 insider tips and tricks, Ajax Hacks covers all of the technology's
finer points Want to build next-generation web applications today? This book can show you how Among the multitude of topics addressed, it shows you techniques for:
maintenance, performance, and reliability for JavaScript code.
The latest in O"Reilly's celebrated Hacks series, Ajax Hacks smartly complements other
Trang 2O'Reilly titles such as Head Rush Ajax and JavaScript: The Definitive Guide.
Trang 3By Bruce W Perry
Publisher: O'Reilly Pub Date: March 2006 Print ISBN-10: 0-596-10169-4 Print ISBN-13: 978-0-59-610169-5 Pages: 438
Trang 7The truth is, I've never built an Ajax application
Sure, I've worked on Ajax projects But when it comes to
programming, my experience is pretty limited I've done someJavaScripting here and there I know a little Perl, but hardlyenough to build a web application As a programmer, I'm more
of an occasional weekend hobbyist than anything else
You can imagine how frustrating it is for people to learn this factwhen they send me emails asking for help with their JavaScript.But you can hardly fault them for expecting me to be a
published on adaptivepath.com, you can see that we're muchmore likely to be talking about ways to analyze user behavior ormake an experience connect with people than about the latestcode libraries or data schemas
That's one reason some people thought it was a little strangefor me to be writing about Ajax at all Designers, one way ofthinking goes, should leave writing about technology to
technologists
But seeing Ajax as a purely technological phenomenon missesthe point If anything, Ajax is even more of a sea change fordesigners than it is for developers Sure, there are a lot of ways
in which developers need to change their thinking as they makethe transition from building traditional web applications to
building Ajax applications But for those of us who design user
Trang 8We've gotten pretty good at our jobs in the last 10 years or so.We've started to get a handle on what the Web does well andwhat the Web does poorly And we've developed an arsenal ofconventions to rely on when we design applications: where thelogo goes, how a link behaves when it is clicked, how to
communicate that something even can be clicked
All of that knowledgewell, most of it, anywaygoes out the
window with Ajax We have a wider palette to work with, butthat also means we have more opportunities to make mistakes.And believe me, we'll make a lot of them It takes time to getsmart, and just as it took us a while to get a handle on the oldstatic Web, it'll take us some time to get good at creating Ajaxexperiences as well
And that's where youand this bookcome in
One of the most inspiring things about the Web is that anyonecan contribute to its development Standards bodies and
platform vendors are important, of course, but there is no
master plan for the evolution of the Web The Web goes whereits users want it to gobut only when they're ready Sometimesthat means a great idea doesn't take hold right away, and
sometimes that means it only takes one voice to bring that idea
to an audience ready to hear it
All of us, designers and developers together, are the architects
of the Web Through tools like this book, we can learn fromeach other, and we can use our creativity to spur on furtherinnovation The choices we make now lay the groundwork forwhat is to come At this moment, Ajax is our manifest destiny,the obvious next chapter in the story of the Web When thischapter is over, I'll be excited to see what the next one brings.But for now, let's see what we can do with what we've got
Trang 10About the AuthorContributors
Acknowledgments
Trang 11Bruce Perry is an independent software developer and writer,
and the author of O'Reilly's Java Servlet & JSP Cookbook Since
1996, he has developed web applications and databases forvarious nonprofits, design and marketing firms, as well as
publishers In his spare time, Perry is an active age-group
triathlete and has cycled extensively in the Swiss Alps He lives
in the Newburyport, Massachusetts area with his wife StacyLeBaron, daughter Rachel, and son Scott
Trang 12
Micah Dubinko served as an editor and author of the
XForms 1.0 W3C specification, and he began participating inthe XForms effort in September 1999, nine months beforethe official Working Group was chartered Micah received anInfoWorld Innovator award in 2004 He is the author of
O'Reilly's XForms Essentials, available online at
http://www.xformsinstitute.com Currently, Micah works forYahoo! in California as a senior research developer
Curt Hibbs is a senior software developer in St Louis withmore than 30 years' experience in platforms, languages,and technologies too numerous to list With a keen (andalways searching) eye for new methods and technologies tomake his work easier and more productive, he has becomevery active in the Ruby development community
Brad Neuberg has done extensive work in the open sourcecommunity, contributing code to Mozilla, JXTA, the JakartaFeed Parser, and more His experience includes developing
on Wall Street with distributed systems, n-tier design, andJ2EE As senior software engineer at Rojo Networks, Bradfocused on next-generation aggregators, the blogosphere,MySQL, Ajax, and Lucene Recent work includes consultingfor the Internet Archive to create an Ajax book reader;
focusing on Ajax/DHTML open source frameworks, includingthe Really Simple History library recently adopted by
Google; and working with the Ajax Massive Storage System
(AMASS) and dojo.storage, which allow web applications to
permanently and securely store megabytes of data
Premshree Pillai is a Technical Yahoo! He hacks (maintainsthe Ruby APIs for Yahoo! Web Services, Flickr, Technorati,
Trang 13Commonwealth University
Sean Snider is a senior web software engineer for Yahoo!and the Web User Interface Team manager for Yahoo! MusicUnlimited Sean has been building Ajax applications and richweb sites for over eight years within the music, video game,and e-commerce industries, for companies such as
Electronic Arts (EA Sports, http://www.easports.com),
Musicmatch (Musicmatch Jukebox,
http://www.musicmatch.com), and iVillage.com
Trang 14
My family members play the most important role in giving life
to a book idea, nurturing its writing, and making its final
publication possible First, I thank my parents Anne and RobertPerry, who had the wisdom to settle in Concord, Massachusetts,where books are valued perhaps more than in any other town inthe United States They promoted reading during my childhood
as an activity above most all others, perhaps second only togetting outside and appreciating the environment and MotherNature
Second, I would like to thank my wife Stacy and children Racheland Scott, who exhibited great patience while dealing with themodest crises of publication deadlines, such as the temporaryloss of their husband and father to the inner sanctorum of ahome office, or the occasional over-cooking of the peas as Iraced back to my lap top to complete some unfinished
paragraph
I'd like to thank my O'Reilly editor Simon St.Laurent, who
tirelessly steered this book to publication from beginning to
end, and offered cogent advice during the entire duration ofwriting, despite the challenging time line This book greatly
benefited from the technical reviews initiated by Micah Dubinko,Shelley Powers, Thinakorn Tabtieng, and Michael Buffington.They demonstrated impressive versatility in taking both a longview of the book's topic, as well as focusing on numerous fine-grained details that required corrections or greater exposition
Trang 15
Ajax, a term coined in 2005 to describe the combination of a
group of popular web technologies, has been an instant hit inthe software world Instant success can raise many doubts, but
it would be a mistake to view this software model as simply thelatest "next big thing" to make a big splash and then vanish intothe ether of the Web
Why? First of all, Ajax's interweaved technologies, including
JavaScript, the Document Object Model (DOM), and CascadingStyle Sheets (CSS), live in the world of the Web, where newinformation and technologies hit millions of people in
milliseconds If the technique represents an interesting ideawith practical merit, a good probability exists that developerswill at least dip their toes into the technology's waters, if notimmediately add the new tool to their code arsenals Second,the Ajax family of techniques are already well known and opensource, or free of charge; therefore, few barriers exist to tryingthem out for at least a prototype version of new software
Third, a number of useful, well-known applications are based onAjax, such as Flickr and Gmail Fourth, web users are alreadyaccustomed to an Ajax application's desktop-like experience,where the application can make client/server connections
without completely changing the browser page
There are numerous other reasons why Ajax is here to stay,such as the excellent support for JavaScript, CSS, and DOM
provided by modern browsers such as Firefox, as well as thepros and cons of using Macromedia Flash for Rich Internet
Applications instead
Trang 16The "single-page application" represented by Ajax, with
client/server connections that do not interrupt the user's
experience and dynamically change elements in different webpage regions, is appropriate for numerous uses, such as blogs,learning tools, online newsletters, and small web portals or
communities Many of these types of sites are already built
using Ajax techniques Ajax can also improve the user
experience in large web-based client/server applications thatextend beyond the single-page model
The time between the conception of this book and the writing ofthis preface has seen Ajax morph into a software platform thatdominates headlines on the Web, not to mention the birth ofnew acronyms such as Ajaj (Asynchronous JavaScript and
JSON) and lingo such as "Ajaxy" (as in an Ajaxy server
connection) Software innovations and human language seem toshare the same organic dynamic
Trang 17
Ajax Hacks was written by yours truly and seven different
contributors, many of whom are among the innovators,
bloggers, and early adopters who helped give Ajax and its opensource tools the boost it enjoys today They are senior web
engineers and developers whose homes stretch from Bangalore
to San Francisco, a scope reflecting the diverse and
serendipitous nature by which the writers found this book andthe book discovered its writers (See the Credits for more
details on these writers.)
Ajax Hacks collects not only dozens of easy-to-grasp, cutting-edge explorations of Ajax technology, such as Google/Yahoo!mapping mash-ups, drag-and-drop bookstores, and single-pageweb services apps, but a large number of hacks that represent
practical advice for Ajax developers Ajax Hacks also introduces
JavaScript newbies and aficionados alike to useful code
libraries, including Prototype, Rico, and script.aculo.us Chapter
7 focuses on a practical and new web application frameworkwith excellent Ajax tools including Ruby on Rails
A number of the contributions are hacks in the original, cleversense of the term, exploring topics such as using algorithmsand Flash objects to simulate a browser history list and storeAjax-related data offline, configuring Apache to fix the
inside your browser, and mashing up Yahoo! Maps with a
location-to-URL service called GeoURL
Some of the contributed hacks illustrate cool web controls andembedded scripts, such as a hack that scripts an auto-completefield from scratch, a hack that creates JavaScript bookmarkletsthat do not have size limitations, and another that creates anRSS feed reader for an Ajax application These are hacks thatpush the envelope, just as we approach the cusp of this web
Trang 18distributed as open source libraries, for their own applications
Trang 19
You can read this book from cover to cover if you like, but forthe most part, each hack stands on its own, so feel free to
browse and jump to the different sections that interest you
most If there's a prerequisite you need to know about, a crossreference will guide you to the right hack So, feel free to
browse, flipping around to whatever sections interest you most
Trang 20The book is divided into several chapters, organized by subject:
Chapter 1, Ajax Basics
What is Ajax? This chapter begins with a synopsis of thegroup of well-known technologies that make up Ajax Thechapter's hacks introduce the XMLHttpRequest JavaScript objectand its properties and methods, then delve into the meat ofthe matter, such as sending GET and POST requests, as well
as receiving data in plain text, XML, and JSON format Thischapter also illustrates the dynamic scripting of CSS styles
in Ajax applications Let the users change the colors andfonts inside the browser page!
Chapter 2, Web Forms
Web forms have certainly changed in the Ajax world Asrevealed in this chapter's hacks, it is typical now to submitform data and to build form widgets such as select lists andcheckbox groups using server data fetched in the
background with XMLHttpRequest Because the page doesn'thave to be completely rebuilt from a server response, theuser experiences few application delays These hacks showhow to submit text from form fields and textareas and
display server values in those fields, without making theuser click a submit button The hacks also generate variouselements, such as select lists and unordered lists, using
server
Trang 21Ajax applications can cut down on server hits by validatingthe format of email addresses, credit card numbers, zip
codes, and other types of data that users enter into webforms before sending the data A server component is
world application; however, the application may implement
obviously necessary for final credit card validation in a real-a "first layer of defense," as in these hacks, by validatingthe formats of text-field values with JavaScript regular
expressions
Chapter 4, Power Hacks for Web Developers
Web developers have never had cooler, easier-to-work-withtools than the Yahoo! and Google web APIs This chapterincludes a mash-up of Google Maps, Yahoo! Maps, and
Yahoo! driving directions, as well as a software interactioninvolving Yahoo! Maps and a location-to-URL service calledGeoURL It also features more prosaic, pragmatic web
hacks, such as sending an email with XMLHttpRequest; viewing,creating, and sending HTTP cookies with client-side script;fetching a postal code dynamically without altering the webpage; as well as discovering and displaying the browser'slocale information
Trang 22populate select lists from Java arrays and Maps; call customJava objects from their JavaScript proxies or counterparts;and use JavaScript objects to call built-in Java objects Thischapter is a treat for developers who are immersed in bothJava and JavaScript
Chapter 6, Hack Ajax with the Prototype and Rico Libraries
The hacks in this chapter use Prototype, a cool open sourceJavaScript library that includes its own Ajax tools You'll seehow to update DOM elements in a web page with serverdata using Prototype's Ajax.Updater object, and how to use
timed intervals while another "observer" object monitors atext field for changes (imagine: a user enters data into textfields, and a JavaScript object automatically sends the dataoff to persistent server storage whenever the field valuechanges) Another hack in this chapter uses the open
source library Rico in a Weather.com web services
and-drop bookstore, also using Rico
application Finally, the chapter's last hack sets up a drag-Chapter 7, Work with Ajax and Ruby on Rails
Learn Ruby on Rails! Ruby on Rails (RoR) is an efficient andwell-designed web application framework, based on theModel-View-Controller design pattern, that made its debut
in 2005 This chapter begins with a simple hack that helpsyou get up and running with RoR, then moves on to severalhacks that illustrate RoR's Ajax tools Each hack is a webapplication task written in Ruby; for example, one of thehacks monitors a server connection and displays the status
in the client RoR bundles Prototype with the framework,
Trang 23an auto-complete field based on a script.aculo.us object; a
control that allows the user to edit textual content in thebrowser and then save the changes on a server, without aweb page round trip; and, just for fun, a web form that
Trang 24The following is a list of the typographical conventions used inthis book:
Italics
Used to indicate URLs, filenames, filename extensions, anddirectory/folder names, e.g., a path in the filesystem
appears as /Developer/Applications
Constant width
Used to show code examples, the contents of files, consoleoutput, as well as the names of variables, commands, andother code excerpts
Trang 25supplementary information about the topic at hand
This is a warning or note of caution, often indicating that something might break if you're not careful, possibly quite badly.
The thermometer icons, found next to each hack, indicate therelative complexity of the hack:
Whenever possible, the hacks in this book are not platform-specific, which means you can use them on Linux, Macintosh,
and Windows machines However, some things are possible only
on a particular platform
Trang 26This book is here to help you get your job done In general, youmay use the code in this book in your programs and
documentation You do not need to contact us for permissionunless you're reproducing a significant portion of the code Forexample, writing a program that uses several chunks of codefrom this book does not require permission Selling or
distributing a CD-ROM of examples from O'Reilly books does
require permission Answering a question by citing this bookand quoting example code does not require permission
Incorporating a significant amount of example code from this
book into your product's documentation does require
permission
We appreciate, but do not require, attribution An attributionusually includes the title, author, publisher, and ISBN For
example: "Ajax Hacks by Bruce Perry Copyright 2006 O'Reilly
Media, Inc., 0-596-10169-4."
If you feel your use of code examples falls outside fair use orthe permission given above, feel free to contact us at
permissions@oreilly.com
Trang 27When you see a Safari® Enabled icon on the cover of yourfavorite technology book, it means the book is available onlinethrough the O'Reilly Network Safari Bookshelf
Safari offers a solution that's better than e-books It's a virtuallibrary that lets you easily search thousands of top technologybooks, cut and paste code samples, download chapters, andfind quick answers when you need the most accurate, currentinformation Try it for free at http://safari.oreilly.com
Trang 28We have tested and verified the information in this book to thebest of our ability, but you may find that features have changed(or even that we have made mistakes!) As a reader of this
book, you can help us to improve future editions by sending usyour feedback Please let us know about any errors,
inaccuracies, bugs, misleading or confusing statements, andtypos that you find anywhere in this book
Please also let us know what we can do to make this book moreuseful to you We take your comments seriously and will try toincorporate reasonable suggestions into future editions You canwrite to us at:
Trang 30To explore Hacks books online or to contribute a hack for futuretitles, visit:
http://hacks.oreilly.com
Trang 31Remember when users called the Internet the "world wide
wait?" Way back in the Neolithic era of the Web? With someapplications, that aspect of the Web hasn't really changed thatmuch: fill out form, click button, web page goes away, wait,page refreshes, correct mistake, click, wait, wait You've beenstuck in this limbo before
A number of recent web sites, however, such as many of thecool mapping applications that have evolved of late, requiremuch greater responsiveness in the way they interact with
users The old, conventional way of handling user interaction is
to have the entire page "go away" with every click, with thenew page reappearing in the browser view only when the
server's response is finally complete However, some new
applications require small pieces of the web page to changeinstantaneously, without the entire page reloading
For example, if you have ever used Google Maps, the way youcan drag outlying regions into your view conveys the impressionthat you have all of the maps stored locally on your computer,for your effortless manipulation Imagine how unpopular thisapplication would be if every time you tried to "drag" the mapthe page disappeared for a few (long) moments while the
browser waited for another server response The applicationwould be so sluggish that no one would use it So what's themagic that makes this work?
Trang 32A blend of well-known technologies and a nifty JavaScript toolform the basis of a snappier and more powerful application
model for the Web If you're afraid of acronym overload, don't
worrythis one's easy It's called Ajax, which stands for
Asynchronous JavaScript and XML
Ajax is neither a floor wax nor a desert topping (nor, indeed, alemon-scented cleaning product!) It's a blend of a number ofstandard technologies already familiar to developers and
designers:
JavaScript, a programming language that adds dynamicscripting to web pages JavaScript code can be embedded in
Extensible Markup Language (XML), a language designed
to define other languages The XMLHttpRequest object can
handle the server response in standard XML format as well
Trang 33HTML and Cascading Style Sheets (CSS), which control
what the user sees on a web page Web developers can useJavaScript to make dynamic changes to the visual interface
by programming HTML elements and CSS styles
The Document Object Model (DOM), a model that
represents an XML file or web page as a set of related
objects that can be dynamically manipulated, even after theuser has downloaded the page The web page view is
structured as a tree hierarchy made up of a root node, the parent, and its various branches, or children Each HTML
object, with Version 5.0 of the Internet Explorer browser (as ofthis writing, IE is on Version 6, with v7 in a beta release)
The plethora of new web applications that use Ajax, however,suggests that this group of technologies has morphed into anew web model "Web 2.0" is next-generation-speak
encompassing Ajax, a form of Rich Internet Application (so
called because much of the application's functionality can reside
in the client browser) Examples of these applications are
Google Maps, Gmail, a collaboration suite called Zimbra, aninteresting personal search-engine tool called Rollyo
(http://www.rollyo.com), and one of the first interactive web
Trang 34http://map.search.ch/index.en.html) The number of Ajax
applications is growing very rapidly You can find a short list onWikipedia, at
http://en.wikipedia.org/wiki/List_of_websites_using_Ajax
Trang 35
Of course, Ajax is not for everyone (particularly those desserttopping fans!) Because Ajax technology can dynamically alter aweb page that has already been downloaded, it may interferewith certain functions near and dear to many users, such ascreating bookmarks for browser views For example, in the
absence of fancy scripting solutions, the dynamic changes youmake with DOM in an existing web page cannot be linked towith a URL that you can send to your friends or save for later.(Both "Fix the Browser Back Button in Ajax Applications" [Hack
#68] and "Handle Bookmarks and Back Buttons with RSH"
[Hack #69] should help shed light on these issues and providesome hackable solutions.)
A number of the cool Ajax tips described in this book alter thebehavior of many familiar web widgets, such as select lists,
data and talk to servers behind the scenes However, bear inmind that Ajax-powered widgets should be first and foremost
usable, and always avoid confusing and irritating web users.
Trang 36At the center of many of the hacks in this book is the
server data while the user is happily playing with the rest ofyour application This object has its own API, which we will
summarize in this introduction
"Detect Browser Compatibility with the Request Object" [Hack
#1] covers setting up the request object in JavaScript Once theobject is initialized, it has several methods and properties thatyou can use in your own hacks
A common practice among programming types is to call the functions that are associated with particular JavaScript objects "methods." The XMLHttpRequest object's methods include open( ), send( ), and abort( ).
The following list shows the properties supported by the requestobjects defined by most of the major browsers, such as InternetExplorer 5.0 and later, Safari 1.3 and 2.0, Netscape 7, and
Opera's latest releases (such as Opera 8.5) Mozilla Firefox'srequest object has additional properties and methods not
shared by the request objects of other major browsers,[2] but italso supports all of the following:
[2] The Mozilla Firefox XMLHttpRequest object has onload , onprogress , and onerror properties that are event listener types Firefox has also defined addEventListener( ) , dispatchEvent( ) ,
overrideMimeType( ) , and removeEventListener( ) methods See
http://www.xulplanet.com/references/objref/XMLHttpRequest.html for more details on these Firefox request
object members.
onreadystatechange
Trang 37Callback function; the function assigned to this property iscalled whenever readyState changes.
Trang 39Hack 1 Detect Browser Compatibility with the Request Object
The programming tool that allows Ajax applications to makeHTTP requests to a server is an object that you can use fromwithin JavaScript code In the world of Firefox and Netscape (aswell as Safari and Opera), this object is named XMLHttpRequest.However, continuing with the tradition established by IE 5.0,recent vintages of Internet Explorer implement the software as
Microsoft.XMLHTTP and Msxml2.XMLHTTP refer to different versions of software components that are a part of Microsoft XML Core Services (MSXML).
Here's what our contributing IE expert says on this matter:
"If you use Microsoft.XMLHTTP, the ActiveXObject wrapper will try to initialize the last known good version of the object that has this program (or "prog") ID This object, in theory, could be MSXML 1.0, but almost no one these days has that version because it has been updated via Windows Update, IE 6, or another means MSXML 1.0 was very short-lived If you use MSXML2.XMLHTTP, that signifies to the wrapper to use at least MSXML 2.0 libraries Most developers do not need to use a specific version of MSXML, such as MSXML2.XMLHTTP.4.0 or
MSXML2.XMLHTTP.5.0."
Trang 40code is window.XMLHttpRequest The compatibility check for thesebrowser types looks like this: