Tải bản đầy đủ (.pdf) (725 trang)

OReilly AJAX hacks tips and tools for creating responsive websites mar 2006 ISBN 0596101694

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (6.87 MB, 725 trang )

AjaxHacks
ByBruceW.Perry
...............................................
Publisher:O'Reilly
PubDate:March2006
PrintISBN-10:0-596-10169-4
PrintISBN-13:978-0-59-610169-5
Pages:438

TableofContents|Index

Ajax,thepopulartermforAsynchronousJavaScriptandXML,isoneofthemostimportant
combinationsoftechnologiesforwebdeveloperstoknowthesedays.Withitsrich
groupingoftechnologies,Ajaxdeveloperscancreateinteractivewebapplicationswith
XML-basedwebservices,usingJavaScriptinthebrowsertoprocessthewebserver
response.
TakingcompleteadvantageofAjax,however,requiressomethingmorethanyourtypical
"how-to"book.WhatitcallsforisAjaxHacksfromO'Reilly.Thisvaluableguideprovides
direct,hands-onsolutionsthattakethemysteryoutofAjax'smanycapabilities.Eachhack
representsacleverwaytoaccomplishaspecifictask,savingyoucountlesshoursof
searchingfortherightanswer.
Asmartcollectionof100insidertipsandtricks,AjaxHackscoversallofthetechnology's
finerpoints.Wanttobuildnext-generationwebapplicationstoday?Thisbookcanshow
youhow.Amongthemultitudeoftopicsaddressed,itshowsyoutechniquesfor:
UsingAjaxwithGoogleMapsandYahooMaps
DisplayingWeather.comdata
Scrapingstockquotes
Fetchingpostalcodes
Buildingwebformswithauto-completefunctionality
AjaxHacksalsofeaturesanumberofadvancedhacksforacceleratedwebdevelopers.
Discoverhowtocreatehuge,maintainablebookmarklets,howtouseclient-sidestorage


forAjaxapplications,andhowtocallabuilt-inJavaobjectfromJavaScriptusingAjax.The
bookevenaddressesbestpracticesfortestingAjaxapplicationsandimproving
maintenance,performance,andreliabilityforJavaScriptcode.
ThelatestinO"Reilly'scelebratedHacksseries,AjaxHackssmartlycomplementsother


O'ReillytitlessuchasHeadRushAjaxandJavaScript:TheDefinitiveGuide.


AjaxHacks
ByBruceW.Perry
...............................................
Publisher:O'Reilly
PubDate:March2006
PrintISBN-10:0-596-10169-4
PrintISBN-13:978-0-59-610169-5
Pages:438

TableofContents|Index

















































Foreword
creditsCredits
AbouttheAuthor
Contributors
Acknowledgments
Preface
BuildingSingle-PageApplications
ExplainingAjax
HowtoUseThisBook
HowThisBookIsOrganized
ConventionsUsedinThisBook
UsingCodeExamples
SafariEnabled
HowtoContactUs
GotaHack?
Chapter1.AjaxBasics
It'sNotaFloorWax
HandlewithCare
XMLHttpRequest
Hack1.DetectBrowserCompatibilitywiththeRequestObject
Hack2.UsetheRequestObjecttoPOSTDatatotheServer
Hack3.UseYourOwnLibraryforXMLHttpRequest
Hack4.ReceiveDataasXML
Hack5.GetPlainOldStrings
















































































Hack6.ReceiveDataasaNumber
Hack7.ReceiveDatainJSONFormat
Hack8.HandleRequestObjectErrors
Hack9.DigintotheHTTPResponse
Hack10.GenerateaStyledMessagewithaCSSFile
Hack11.GenerateaStyledUserMessageontheFly
Chapter2.WebForms
Hack12.SubmitTextFieldortextareaValuestotheServerWithoutaBrowser
Refresh
Hack13.DisplayTextFieldortextareaValuesUsingServerData
Hack14.SubmitSelection-ListValuestotheServerWithoutaRoundTrip
Hack15.DynamicallyGenerateaNewSelectionListUsingServerData
Hack16.ExtendanExistingSelectionList

Hack17.SubmitCheckboxValuestotheServerWithoutaRoundTrip
Hack18.DynamicallyGenerateaNewCheckboxGroupwithServerData
Hack19.PopulateanExistingCheckboxGroupfromtheServer
Hack20.ChangeUnorderedListsUsinganHTTPResponse
Hack21.SubmitHiddenTagValuestoaServerComponent
Chapter3.Validation
Hack22.ValidateaTextFieldortextareaforBlankFields
Hack23.ValidateEmailSyntax
Hack24.ValidateUniqueUsernames
Hack25.ValidateCreditCardNumbers
Hack26.ValidateCreditCardSecurityCodes
Hack27.ValidateaPostalCode
Chapter4.PowerHacksforWebDevelopers
Hack28.GetAccesstotheGoogleMapsAPI
Hack29.UsetheGoogleMapsAPIRequestObject
Hack30.UseAjaxwithaGoogleMapsandYahoo!MapsMash-up
Hack31.DisplayaWeather.comXMLDataFeed
Hack32.UseAjaxwithaYahoo!MapsandGeoURLMash-up
Hack33.DebugAjax-GeneratedTagsinFirefox
Hack34.FetchaPostalCode
Hack35.CreateLarge,MaintainableBookmarklets
Hack36.UsePermanentClient-SideStorageforAjaxApplications
Hack37.ControlBrowserHistorywithiframes
Hack38.SendCookieValuestoaServerProgram
Hack39.UseXMLHttpRequesttoScrapeanEnergyPricefromaWebPage
Hack40.SendanEmailwithXMLHttpRequest














































































Hack41.FindtheBrowser'sLocaleInformation
Hack42.CreateanRSSFeedReader
Chapter5.DirectWebRemoting(DWR)forJavaJocks
Hack43.IntegrateDWRintoYourJavaWebApplication
Hack44.UseDWRtoPopulateaSelectionListfromaJavaArray
Hack45.UseDWRtoCreateaSelectionListfromaJavaMap
Hack46.DisplaytheKeys/ValuesfromaJavaHashMaponaWebPage
Hack47.UseDWRtoPopulateanOrderedListfromaJavaArray
Hack48.AccessaCustomJavaObjectwithJavaScript
Hack49.CallaBuilt-inJavaObjectfromJavaScriptUsingDWR
Chapter6.HackAjaxwiththePrototypeandRicoLibraries
Hack50.UsePrototype'sAjaxToolswithYourApplication
Hack51.UpdateanHTMLElement'sContentfromtheServer
Hack52.CreateObserversforWebPageFields
Hack53.UseRicotoUpdateSeveralElementswithOneAjaxResponse
Hack54.CreateaDrag-and-DropBookstore
Chapter7.WorkwithAjaxandRubyonRails
SensibleMVC
Hack55.InstallRubyonRails

Hack56.MonitorRemoteCallswithRails
Hack57.MakeYourJavaScriptAvailabletoRailsApplications
Hack58.DynamicallyGenerateaSelectionListinaRailsTemplate
Hack59.FindOutWhetherAjaxIsCallingintheRequest
Hack60.DynamicallyGenerateaSelectionListUsingDatabaseData
Hack61.PeriodicallyMakeaRemoteCall
Hack62.DynamicallyViewRequestInformationforXMLHttpRequest
Chapter8.Savorthescript.aculo.usJavaScriptLibrary
Hack63.Integratescript.aculo.usVisualEffectswithanAjaxApplication
Hack64.CreateaLoginBoxThatShrugsOffInvalidLogins
Hack65.CreateanAuto-CompleteFieldwithscript.aculo.us
Hack66.CreateanIn-PlaceEditorField
Hack67.CreateaWebFormThatDisappearsWhenSubmitted
Chapter9.OptionsandEfficiencies
Hack68.FixtheBrowserBackButtoninAjaxApplications
Hack69.HandleBookmarksandBackButtonswithRSH
Hack70.SetaTimeLimitfortheHTTPRequest
Hack71.ImproveMaintainability,Performance,andReliabilityforLarge
JavaScriptApplications
Hack72.ObfuscateJavaScriptandAjaxCode





















Hack73.UseaDynamicscriptTagtoMakeWebServicesRequests
Hack74.ConfigureApachetoDealwithCross-DomainIssues
Hack75.RunaSearchEngineInsideYourBrowser
Hack76.UseDeclarativeMarkupInsteadofScriptviaXForms
Hack77.BuildaClient-SideCache
Hack78.CreateanAuto-CompleteField
Hack79.DynamicallyDisplayMoreInformationAboutaTopic
Hack80.UseStringsandArraystoDynamicallyGenerateHTML
Index


Foreword
Thetruthis,I'veneverbuiltanAjaxapplication.
Sure,I'veworkedonAjaxprojects.Butwhenitcomesto
programming,myexperienceisprettylimited.I'vedonesome
JavaScriptinghereandthere.IknowalittlePerl,buthardly
enoughtobuildawebapplication.Asaprogrammer,I'mmore
ofanoccasionalweekendhobbyistthananythingelse.
Youcanimaginehowfrustratingitisforpeopletolearnthisfact
whentheysendmeemailsaskingforhelpwiththeirJavaScript.

Butyoucanhardlyfaultthemforexpectingmetobea
technologist.Afterall,Iwroteanarticlecoiningtheterm
"Ajax,"andAjaxisallabouttechnology,right?
ThefunnythingisthatIdidn'tseeitthatwaywhenIwas
writingtheessay.Ididn'tthinkIwaswritingfortechnologists
atall.I'madesigner,andIthoughtIwaswritingforadesign
audience.Ifyoulookatsomeoftheotherthingswe've
publishedonadaptivepath.com,youcanseethatwe'remuch
morelikelytobetalkingaboutwaystoanalyzeuserbehavioror
makeanexperienceconnectwithpeoplethanaboutthelatest
codelibrariesordataschemas.
That'sonereasonsomepeoplethoughtitwasalittlestrange
formetobewritingaboutAjaxatall.Designers,onewayof
thinkinggoes,shouldleavewritingabouttechnologyto
technologists.
ButseeingAjaxasapurelytechnologicalphenomenonmisses
thepoint.Ifanything,Ajaxisevenmoreofaseachangefor
designersthanitisfordevelopers.Sure,therearealotofways
inwhichdevelopersneedtochangetheirthinkingastheymake
thetransitionfrombuildingtraditionalwebapplicationsto
buildingAjaxapplications.Butforthoseofuswhodesignuser


experiences,thechangebroughtaboutbyAjaxisevenmore
profound.
We'vegottenprettygoodatourjobsinthelast10yearsorso.
We'vestartedtogetahandleonwhattheWebdoeswelland
whattheWebdoespoorly.Andwe'vedevelopedanarsenalof
conventionstorelyonwhenwedesignapplications:wherethe
logogoes,howalinkbehaveswhenitisclicked,howto

communicatethatsomethingevencanbeclicked...
Allofthatknowledgewell,mostofit,anywaygoesoutthe
windowwithAjax.Wehaveawiderpalettetoworkwith,but
thatalsomeanswehavemoreopportunitiestomakemistakes.
Andbelieveme,we'llmakealotofthem.Ittakestimetoget
smart,andjustasittookusawhiletogetahandleontheold
staticWeb,it'lltakeussometimetogetgoodatcreatingAjax
experiencesaswell.
Andthat'swhereyouandthisbookcomein.
OneofthemostinspiringthingsabouttheWebisthatanyone
cancontributetoitsdevelopment.Standardsbodiesand
platformvendorsareimportant,ofcourse,butthereisno
masterplanfortheevolutionoftheWeb.TheWebgoeswhere
itsuserswantittogobutonlywhenthey'reready.Sometimes
thatmeansagreatideadoesn'ttakeholdrightaway,and
sometimesthatmeansitonlytakesonevoicetobringthatidea
toanaudiencereadytohearit.
Allofus,designersanddeveloperstogether,arethearchitects
oftheWeb.Throughtoolslikethisbook,wecanlearnfrom
eachother,andwecanuseourcreativitytospuronfurther
innovation.Thechoiceswemakenowlaythegroundworkfor
whatistocome.Atthismoment,Ajaxisourmanifestdestiny,
theobviousnextchapterinthestoryoftheWeb.Whenthis
chapterisover,I'llbeexcitedtoseewhatthenextonebrings.
Butfornow,let'sseewhatwecandowithwhatwe'vegot.


Nowgetoutthere,andgethacking!
JesseJamesGarrett
SanFrancisco,CA

December2005




Credits
AbouttheAuthor
Contributors
Acknowledgments


AbouttheAuthor
BrucePerryisanindependentsoftwaredeveloperandwriter,
andtheauthorofO'Reilly'sJavaServlet&JSPCookbook.Since
1996,hehasdevelopedwebapplicationsanddatabasesfor
variousnonprofits,designandmarketingfirms,aswellas
publishers.Inhissparetime,Perryisanactiveage-group
triathleteandhascycledextensivelyintheSwissAlps.Helives
intheNewburyport,MassachusettsareawithhiswifeStacy
LeBaron,daughterRachel,andsonScott.




Contributors
MicahDubinkoservedasaneditorandauthorofthe
XForms1.0W3Cspecification,andhebeganparticipatingin
theXFormseffortinSeptember1999,ninemonthsbefore
theofficialWorkingGroupwaschartered.Micahreceivedan
InfoWorldInnovatorawardin2004.Heistheauthorof

O'Reilly'sXFormsEssentials,availableonlineat
.Currently,Micahworksfor
Yahoo!inCaliforniaasaseniorresearchdeveloper.
CurtHibbsisaseniorsoftwaredeveloperinSt.Louiswith
morethan30years'experienceinplatforms,languages,
andtechnologiestoonumeroustolist.Withakeen(and
alwayssearching)eyefornewmethodsandtechnologiesto
makehisworkeasierandmoreproductive,hehasbecome
veryactiveintheRubydevelopmentcommunity.
BradNeuberghasdoneextensiveworkintheopensource
community,contributingcodetoMozilla,JXTA,theJakarta
FeedParser,andmore.Hisexperienceincludesdeveloping
onWallStreetwithdistributedsystems,n-tierdesign,and
J2EE.AsseniorsoftwareengineeratRojoNetworks,Brad
focusedonnext-generationaggregators,theblogosphere,
MySQL,Ajax,andLucene.Recentworkincludesconsulting
fortheInternetArchivetocreateanAjaxbookreader;
focusingonAjax/DHTMLopensourceframeworks,including
theReallySimpleHistorylibraryrecentlyadoptedby
Google;andworkingwiththeAjaxMassiveStorageSystem
(AMASS)anddojo.storage,whichallowwebapplicationsto
permanentlyandsecurelystoremegabytesofdata.
PremshreePillaiisaTechnicalYahoo!.Hehacks(maintains
theRubyAPIsforYahoo!WebServices,Flickr,Technorati,


etc.),writes("RubyCorner,"acolumnforLinuxForYou),
andtalks(atvariousconferences)aboutRubyinhisfree
time.HehaspreviouslycontributedtoO'Reilly'sPython
CookbookandYahoo!Hacks,andtotheACM'sCrossroads.

MarkPruettisaprogrammerandwriterlivinginVirginia,
whereheworksforaFortune500energycompany.He's
theauthoroftwobooksandnumerousarticleson
programmingandtechnology.Markreceivedhismasterof
sciencedegreeincomputersciencefromVirginia
CommonwealthUniversity.
SeanSniderisaseniorwebsoftwareengineerforYahoo!
andtheWebUserInterfaceTeammanagerforYahoo!Music
Unlimited.SeanhasbeenbuildingAjaxapplicationsandrich
websitesforovereightyearswithinthemusic,videogame,
ande-commerceindustries,forcompaniessuchas
ElectronicArts(EASports,),
Musicmatch(MusicmatchJukebox,
),andiVillage.com.




Acknowledgments
Myfamilymembersplaythemostimportantroleingivinglife
toabookidea,nurturingitswriting,andmakingitsfinal
publicationpossible.First,IthankmyparentsAnneandRobert
Perry,whohadthewisdomtosettleinConcord,Massachusetts,
wherebooksarevaluedperhapsmorethaninanyothertownin
theUnitedStates.Theypromotedreadingduringmychildhood
asanactivityabovemostallothers,perhapssecondonlyto
gettingoutsideandappreciatingtheenvironmentandMother
Nature.
Second,IwouldliketothankmywifeStacyandchildrenRachel
andScott,whoexhibitedgreatpatiencewhiledealingwiththe

modestcrisesofpublicationdeadlines,suchasthetemporary
lossoftheirhusbandandfathertotheinnersanctorumofa
homeoffice,ortheoccasionalover-cookingofthepeasasI
racedbacktomylaptoptocompletesomeunfinished
paragraph.
I'dliketothankmyO'ReillyeditorSimonSt.Laurent,who
tirelesslysteeredthisbooktopublicationfrombeginningto
end,andofferedcogentadviceduringtheentiredurationof
writing,despitethechallengingtimeline.Thisbookgreatly
benefitedfromthetechnicalreviewsinitiatedbyMicahDubinko,
ShelleyPowers,ThinakornTabtieng,andMichaelBuffington.
Theydemonstratedimpressiveversatilityintakingbothalong
viewofthebook'stopic,aswellasfocusingonnumerousfinegraineddetailsthatrequiredcorrectionsorgreaterexposition.




Preface
Ajax,atermcoinedin2005todescribethecombinationofa
groupofpopularwebtechnologies,hasbeenaninstanthitin
thesoftwareworld.Instantsuccesscanraisemanydoubts,but
itwouldbeamistaketoviewthissoftwaremodelassimplythe
latest"nextbigthing"tomakeabigsplashandthenvanishinto
theetheroftheWeb.
Why?Firstofall,Ajax'sinterweavedtechnologies,including
JavaScript,theDocumentObjectModel(DOM),andCascading
StyleSheets(CSS),liveintheworldoftheWeb,wherenew
informationandtechnologieshitmillionsofpeoplein
milliseconds.Ifthetechniquerepresentsaninterestingidea
withpracticalmerit,agoodprobabilityexiststhatdevelopers

willatleastdiptheirtoesintothetechnology'swaters,ifnot
immediatelyaddthenewtooltotheircodearsenals.Second,
theAjaxfamilyoftechniquesarealreadywellknownandopen
source,orfreeofcharge;therefore,fewbarriersexisttotrying
themoutforatleastaprototypeversionofnewsoftware.
Third,anumberofuseful,well-knownapplicationsarebasedon
Ajax,suchasFlickrandGmail.Fourth,webusersarealready
accustomedtoanAjaxapplication'sdesktop-likeexperience,
wheretheapplicationcanmakeclient/serverconnections
withoutcompletelychangingthebrowserpage.
TherearenumerousotherreasonswhyAjaxisheretostay,
suchastheexcellentsupportforJavaScript,CSS,andDOM
providedbymodernbrowserssuchasFirefox,aswellasthe
prosandconsofusingMacromediaFlashforRichInternet
Applicationsinstead.


BuildingSingle-PageApplications
The"single-pageapplication"representedbyAjax,with
client/serverconnectionsthatdonotinterrupttheuser's
experienceanddynamicallychangeelementsindifferentweb
pageregions,isappropriatefornumeroususes,suchasblogs,
learningtools,onlinenewsletters,andsmallwebportalsor
communities.Manyofthesetypesofsitesarealreadybuilt
usingAjaxtechniques.Ajaxcanalsoimprovetheuser
experienceinlargeweb-basedclient/serverapplicationsthat
extendbeyondthesingle-pagemodel.
Thetimebetweentheconceptionofthisbookandthewritingof
thisprefacehasseenAjaxmorphintoasoftwareplatformthat
dominatesheadlinesontheWeb,nottomentionthebirthof

newacronymssuchasAjaj(AsynchronousJavaScriptand
JSON)andlingosuchas"Ajaxy"(asinanAjaxyserver
connection).Softwareinnovationsandhumanlanguageseemto
sharethesameorganicdynamic.




ExplainingAjax
AjaxHackswaswrittenbyyourstrulyandsevendifferent
contributors,manyofwhomareamongtheinnovators,
bloggers,andearlyadopterswhohelpedgiveAjaxanditsopen
sourcetoolstheboostitenjoystoday.Theyareseniorweb
engineersanddeveloperswhosehomesstretchfromBangalore
toSanFrancisco,ascopereflectingthediverseand
serendipitousnaturebywhichthewritersfoundthisbookand
thebookdiscovereditswriters.(SeetheCreditsformore
detailsonthesewriters.)
AjaxHackscollectsnotonlydozensofeasy-to-grasp,cuttingedgeexplorationsofAjaxtechnology,suchasGoogle/Yahoo!
mappingmash-ups,drag-and-dropbookstores,andsingle-page
webservicesapps,butalargenumberofhacksthatrepresent
practicaladviceforAjaxdevelopers.AjaxHacksalsointroduces
JavaScriptnewbiesandaficionadosaliketousefulcode
libraries,includingPrototype,Rico,andscript.aculo.us.Chapter
7focusesonapracticalandnewwebapplicationframework
withexcellentAjaxtoolsincludingRubyonRails.
Anumberofthecontributionsarehacksintheoriginal,clever
senseoftheterm,exploringtopicssuchasusingalgorithms
andFlashobjectstosimulateabrowserhistorylistandstore
Ajax-relateddataoffline,configuringApachetofixthe

XMLHttpRequestcross-domainrestrictions,runningasearchengine
insideyourbrowser,andmashingupYahoo!Mapswitha
location-to-URLservicecalledGeoURL.
Someofthecontributedhacksillustratecoolwebcontrolsand
embeddedscripts,suchasahackthatscriptsanauto-complete
fieldfromscratch,ahackthatcreatesJavaScriptbookmarklets
thatdonothavesizelimitations,andanotherthatcreatesan
RSSfeedreaderforanAjaxapplication.Thesearehacksthat
pushtheenvelope,justasweapproachthecuspofthisweb


model'sformulation.Atthesametime,webdeveloperscan
adaptanumberofthisbook'shacks,someofwhichare
distributedasopensourcelibraries,fortheirownapplications.




HowtoUseThisBook
Youcanreadthisbookfromcovertocoverifyoulike,butfor
themostpart,eachhackstandsonitsown,sofeelfreeto
browseandjumptothedifferentsectionsthatinterestyou
most.Ifthere'saprerequisiteyouneedtoknowabout,across
referencewillguideyoutotherighthack.So,feelfreeto
browse,flippingaroundtowhateversectionsinterestyoumost.


HowThisBookIsOrganized
Thebookisdividedintoseveralchapters,organizedbysubject:


Chapter1,AjaxBasics
WhatisAjax?Thischapterbeginswithasynopsisofthe
groupofwell-knowntechnologiesthatmakeupAjax.The
chapter'shacksintroducetheXMLHttpRequestJavaScriptobject
anditspropertiesandmethods,thendelveintothemeatof
thematter,suchassendingGETandPOSTrequests,aswell
asreceivingdatainplaintext,XML,andJSONformat.This
chapteralsoillustratesthedynamicscriptingofCSSstyles
inAjaxapplications.Lettheuserschangethecolorsand
fontsinsidethebrowserpage!

Chapter2,WebForms
WebformshavecertainlychangedintheAjaxworld.As
revealedinthischapter'shacks,itistypicalnowtosubmit
formdataandtobuildformwidgetssuchasselectlistsand
checkboxgroupsusingserverdatafetchedinthe
backgroundwithXMLHttpRequest.Becausethepagedoesn't
havetobecompletelyrebuiltfromaserverresponse,the
userexperiencesfewapplicationdelays.Thesehacksshow
howtosubmittextfromformfieldsandtextareasand
displayservervaluesinthosefields,withoutmakingthe
userclickasubmitbutton.Thehacksalsogeneratevarious
elements,suchasselectlistsandunorderedlists,using
XMLHttpRequestanddatathatisdynamicallyaccessedfroma
server.


Chapter3,Validation
Ajaxapplicationscancutdownonserverhitsbyvalidating
theformatofemailaddresses,creditcardnumbers,zip

codes,andothertypesofdatathatusersenterintoweb
formsbeforesendingthedata.Aservercomponentis
obviouslynecessaryforfinalcreditcardvalidationinarealworldapplication;however,theapplicationmayimplement
a"firstlayerofdefense,"asinthesehacks,byvalidating
theformatsoftext-fieldvalueswithJavaScriptregular
expressions.

Chapter4,PowerHacksforWebDevelopers
Webdevelopershaveneverhadcooler,easier-to-work-with
toolsthantheYahoo!andGooglewebAPIs.Thischapter
includesamash-upofGoogleMaps,Yahoo!Maps,and
Yahoo!drivingdirections,aswellasasoftwareinteraction
involvingYahoo!Mapsandalocation-to-URLservicecalled
GeoURL.Italsofeaturesmoreprosaic,pragmaticweb
hacks,suchassendinganemailwithXMLHttpRequest;viewing,
creating,andsendingHTTPcookieswithclient-sidescript;
fetchingapostalcodedynamicallywithoutalteringtheweb
page;aswellasdiscoveringanddisplayingthebrowser's
localeinformation.

Chapter5,DirectWebRemoting(DWR)forJavaJocks
DWRisaniftytoolkitthatallowsdeveloperstomake
remotecallstoJavaserverobjectsfromJavaScript,without
anyJavaappletsorplug-ins.DWRusesAjaxrequests
behindthescenes;thetoolkit'susers,however,donothave


todealwithXMLHttpRequestprogramming.Thesehacks
populateselectlistsfromJavaarraysandMaps;callcustom
JavaobjectsfromtheirJavaScriptproxiesorcounterparts;

anduseJavaScriptobjectstocallbuilt-inJavaobjects.This
chapterisatreatfordeveloperswhoareimmersedinboth
JavaandJavaScript.

Chapter6,HackAjaxwiththePrototypeandRicoLibraries
ThehacksinthischapterusePrototype,acoolopensource
JavaScriptlibrarythatincludesitsownAjaxtools.You'llsee
howtoupdateDOMelementsinawebpagewithserver
datausingPrototype'sAjax.Updaterobject,andhowtouse
thePeriodicalExecuterobjecttoexecuteAjaxrequestsat
timedintervalswhileanother"observer"objectmonitorsa
textfieldforchanges(imagine:auserentersdataintotext
fields,andaJavaScriptobjectautomaticallysendsthedata
offtopersistentserverstoragewheneverthefieldvalue
changes).Anotherhackinthischapterusestheopen
sourcelibraryRicoinaWeather.comwebservices
application.Finally,thechapter'slasthacksetsupadragand-dropbookstore,alsousingRico.

Chapter7,WorkwithAjaxandRubyonRails
LearnRubyonRails!RubyonRails(RoR)isanefficientand
well-designedwebapplicationframework,basedonthe
Model-View-Controllerdesignpattern,thatmadeitsdebut
in2005.Thischapterbeginswithasimplehackthathelps
yougetupandrunningwithRoR,thenmovesontoseveral
hacksthatillustrateRoR'sAjaxtools.Eachhackisaweb
applicationtaskwritteninRuby;forexample,oneofthe
hacksmonitorsaserverconnectionanddisplaysthestatus
intheclient.RoRbundlesPrototypewiththeframework,



thenwrapsthesetupoftheAjaxobjectsintoitsowneasyto-learn,embeddedscriptlanguage.Getreadytoreadalot
ofRubycode,atreatforthosewhomaybenewtothis
elegantandpowerfultool!

Chapter8,Savorthescript.aculo.usJavaScriptLibrary
script.aculo.usisanotheropensourceJavaScriptlibrary
builtonPrototype.Itoffersabroadmenuofusefuleffects
andcontrolsfordevelopers.ThesehackscreateaMacOS
Xstyleloginboxthat"shakes"inresponsetoinvalidlogins;
anauto-completefieldbasedonascript.aculo.usobject;a
controlthatallowstheusertoedittextualcontentinthe
browserandthensavethechangesonaserver,withouta
webpageroundtrip;and,justforfun,awebformthat
disappearsinapuffofsmokewhenit'ssubmitted.

Chapter9,OptionsandEfficiencies
Thesehacksprovideseveraltipsforreal-worldAjax
developers.Ironically,severalhacksillustratehowtoavoid
usingXMLHttpRequesttohittheserver:you'llseehowtoruna
searchengineinsidethebrowser,cachedatawith
JavaScript,and"fix"thebrowserbackbuttoninanAjax
applicationbyinternallystoringandaccessingstate.These
hacksalsorecommendwaystocombinecodelibrariesto
increasedownloadspeed,obfuscateorpartiallyobscure
JavaScriptcodetoprotectproprietaryscripting,setatimer
forabortinganAjaxrequest,aswellasdynamicallyrequest
datainJavaScriptObjectNotation(JSON)formatusingthe
HTMLscripttag.



ConventionsUsedinThisBook
Thefollowingisalistofthetypographicalconventionsusedin
thisbook:

Italics
UsedtoindicateURLs,filenames,filenameextensions,and
directory/foldernames,e.g.,apathinthefilesystem
appearsas/Developer/Applications

Constantwidth
Usedtoshowcodeexamples,thecontentsoffiles,console
output,aswellasthenamesofvariables,commands,and
othercodeexcerpts

Constantwidthbold
Usedtohighlightportionsofcode

Graytype
Usedtoindicateacrossreferencewithinthetext
Youshouldpayspecialattentiontonotessetapartfromthe
textwiththefollowingicons:


Thisisatip,suggestion,orgeneralnote.Itcontainsuseful
supplementaryinformationaboutthetopicathand.

Thisisawarningornoteofcaution,oftenindicatingthatsomething
mightbreakifyou'renotcareful,possiblyquitebadly.

Thethermometericons,foundnexttoeachhack,indicatethe

relativecomplexityofthehack:
Wheneverpossible,thehacksinthisbookarenotplatformspecific,whichmeansyoucanusethemonLinux,Macintosh,
andWindowsmachines.However,somethingsarepossibleonly
onaparticularplatform.


×