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

Sams teach yourself AJAX in 10 minutes may 2006 ISBN 0672328682

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 (2.66 MB, 404 trang )

SAMSTeachYourselfAjaxin10Minutes
ByPhilBallard
...............................................
Publisher:Sams
PubDate:April28,2006
PrintISBN-10:0-672-32868-2
PrintISBN-13:978-0-672-32868-8
Pages:240

TableofContents|Index

SamsTeachYourselfAjaxin10Minutes
isaconciseintroductiontothebasicsofbuildingAjaxapplicationsandthearchitecture
andoperationoftheseapplications.YouwilllearnthetechniquesemployedinusingAjax,
introducingAjaxandexplaininghowitmaybeusedtosolverealisticuserinterface
problems.Youwillbeabletoimmediatelybeginbuildingwebapplications,andwillhave
platformfromwhichtoexploremoreadvancedaspectsofAjax.


SAMSTeachYourselfAjaxin10Minutes
ByPhilBallard
...............................................
Publisher:Sams
PubDate:April28,2006
PrintISBN-10:0-672-32868-2
PrintISBN-13:978-0-672-32868-8
Pages:240

TableofContents|Index














































Copyright
AbouttheAuthor
Acknowledgments
WeWanttoHearfromYou!
ReaderServices
Introduction
AboutThisBook
WhatIsAjax?
WhoThisBookIsFor
WhatDoINeedToUseThisBook?
ConventionsUsedinThisBook
OnlineResourcesandErrata
PartI:ARefresheronWebTechnologies
Lesson1.AnatomyofaWebsite
AShortHistoryoftheWeb
WorkingsoftheWorldWideWeb
Summary
Lesson2.WritingWebPagesinHTML

IntroducingHTML
ElementsofanHTMLPage
AMoreAdvancedHTMLPage
SomeUsefulHTMLTags
CascadingStyleSheetsinTwoMinutes
Summary



















































































Lesson3.SendingRequestsUsingHTTP
IntroducingHTTP
TheHTTPRequestandResponse

HTMLForms
Summary
Lesson4.Client-SideCodingUsingJavaScript
AboutJavaScript
InattheDeepEnd
ManipulatingDatainJavaScript
Summary
Lesson5.Server-SideProgramminginPHP
IntroducingPHP
EmbeddingPHPinHTMLPages
VariablesinPHP
ControllingProgramFlow
Summary
Lesson6.ABriefIntroductiontoXML
IntroducingXML
XMLBasics
JavaScriptandXML
TheDocumentObjectModel(DOM)
Summary
PartII:IntroducingAjax
Lesson7.AnatomyofanAjaxApplication
TheNeedforAjax
IntroducingAjax
TheConstituentPartsofAjax
PuttingItAllTogether
Summary
Lesson8.TheXMLHTTPRequestObject
MoreAboutJavaScriptObjects
IntroducingXMLHTTPRequest
CreatingtheXMLHTTPRequestObject

Summary
Lesson9.TalkingwiththeServer
SendingtheServerRequest
MonitoringServerStatus
TheCallbackFunction
Summary



















































































Lesson10.UsingtheReturnedData
TheresponseTextandresponseXMLProperties
AnotherUsefulJavaScriptDOMProperty

ParsingresponseXML
ProvidingUserFeedback
Summary
Lesson11.OurFirstAjaxApplication
ConstructingtheAjaxApplication
TheHTMLDocument
AddingJavaScript
PuttingItAllTogether
Summary
PartIII:MoreComplexAjaxTechnologies
Lesson12.ReturningDataasText
GettingMorefromtheresponseTextProperty
Summary
Lesson13.AHAHAsynchronousHTMLandHTTP
IntroducingAHAH
CreatingaSmallLibraryforAHAH
UsingmyAHAHlib.js
Summary
Lesson14.ReturningDataasXML
Addingthe"x"toAjax
TheresponseXMLProperty
ProjectAnRSSHeadlineReader
Summary
Lesson15.WebServicesandtheRESTProtocol
IntroductiontoWebServices
RESTRepresentationalStateTransfer
UsingRESTinPractice
RESTandAjax
Summary
Lesson16.WebServicesUsingSOAP

IntroducingSOAP(SimpleObjectAccessProtocol)
TheSOAPProtocol
UsingAjaxandSOAP
ReviewingSOAPandREST
Summary
Lesson17.AJavaScriptLibraryforAjax











































































AnAjaxLibrary
ReviewingmyAHAHlib.js
ImplementingOurLibrary
UsingtheLibrary
ExtendingtheLibrary
Summary
Lesson18.Ajax"Gotchas"
CommonAjaxErrors
TheBackButton
BookmarkingandLinks
TellingtheUserThatSomethingIsHappening

MakingAjaxDegradeElegantly
DealingwithSearchEngineSpiders
PointingOutActivePageElements
Don'tUseAjaxWhereIt'sInappropriate
Security
TestCodeAcrossMultiplePlatforms
AjaxWon'tCureaBadDesign
SomeProgrammingGotchas
Summary
PartIV:CommercialandOpenSourceAjaxResources
Lesson19.Theprototype.jsToolkit
Introducingprototype.js
WrappingXMLHTTPRequesttheAjaxObject
ExampleProjectStockPriceReader
Summary
Lesson20.UsingRico
IntroducingRico
Rico'sOtherInterfaceTools
Summary
Lesson21.UsingXOAD
IntroducingXOAD
XOADHTML
AdvancedProgrammingwithXOAD
Summary
Index


Copyright
SAMSTeachYourselfAjaxin10Minutes
Copyright©2006bySamsPublishing

Allrightsreserved.Nopartofthisbookshallbereproduced,
storedinaretrievalsystem,ortransmittedbyanymeans,
electronic,mechanical,photocopying,recording,orotherwise,
withoutwrittenpermissionfromthepublisher.Nopatent
liabilityisassumedwithrespecttotheuseoftheinformation
containedherein.Althougheveryprecautionhasbeentakenin
thepreparationofthisbook,thepublisherandauthorassume
noresponsibilityforerrorsoromissions.Norisanyliability
assumedfordamagesresultingfromtheuseoftheinformation
containedherein.
LibraryofCongressCatalogCardNumber:2005934928
PrintedintheUnitedStatesofAmerica
FirstPrinting:April2006
090807064321

Trademarks
Alltermsmentionedinthisbookthatareknowntobe
trademarksorservicemarkshavebeenappropriately
capitalized.SamsPublishingcannotattesttotheaccuracyof
thisinformation.Useofaterminthisbookshouldnotbe
regardedasaffectingthevalidityofanytrademarkorservice
mark.


WarningandDisclaimer
Everyefforthasbeenmadetomakethisbookascompleteand
asaccurateaspossible,butnowarrantyorfitnessisimplied.
Theinformationprovidedisonan"asis"basis.Theauthorand
thepublishershallhaveneitherliabilitynorresponsibilitytoany
personorentitywithrespecttoanylossordamagesarising

fromtheinformationcontainedinthisbookorfromtheuseof
theCDorprogramsaccompanyingit.

BulkSales
SamsPublishingoffersexcellentdiscountsonthisbookwhen
orderedinquantityforbulkpurchasesorspecialsales.For
moreinformation,pleasecontact
U.S.CorporateandGovernmentSales
1-800-382-3419

ForsalesoutsideoftheU.S.,pleasecontact
InternationalSales

ACQUISITIONSEDITOR
LindaHarrison
DEVELOPMENTEDITOR
DamonJordan
MANAGINGEDITOR


CharlotteClapp
PROJECTEDITOR
SethKerney
COPYEDITOR
GeneilBreeze
INDEXER
KenJohnson
PROOFREADER
LeslieJoseph
TECHNICALEDITOR

BillBercik
PUBLISHINGCOORDINATOR
VanessaEvans
MULTIMEDIADEVELOPER
DanScherf
INTERIORDESIGNER
GaryAdair
COVERDESIGNER
ArenHowell


PAGELAYOUT
TnTDesign

Dedication
ToSue,forherendlesspatienceandsupportduringthewriting
ofthisbookandatallothertimes,too.


AbouttheAuthor
PhilBallardgraduatedin1980withanhonorsdegreein
electronicsfromtheUniversityofLeeds,England.Followingan
earlycareerasaresearchscientistwithamajormultinational,
Philspentafewyearsincommercialandmanagerialroles
withinthehightechnologysector,laterworkingfulltimeasa
softwareengineeringconsultant.
Operatingas"TheMouseWhisperer"
(),Philhasspentrecent
yearsinvolvedsolelyinwebsiteandintranetdesignand
developmentforaninternationalportfolioofclients.Anotherof

hiswebsites,,ishometoanactive
andfast-growingAjaxprogrammingcommunity.
PhiliscurrentlybasedinsoutheastEngland.Inhissparetime,
hestillplaysbassguitarinrockbands,despitebeingeasilyold
enoughtoknowbetter.




Acknowledgments
IwouldliketooffermysincerethanksfortheteamatSams
Publishing,especiallyLindaHarrison,ShelleyJohnston,Damon
Jordan,SethKerney,GeneilBreeze,andAndreaBledsoe.
BillBercikdeservesspecialthanks,notonlyforhisexcellent
workastechnicaleditor,butalsoforhisarticleat
thatinspiredmyinterestinAjaxin
thefirstplace.
Iwouldalsoliketoexpressmygratitudetothecountless
individualswhohavesharedtheirknowledgeandskillbywriting
opensourcesoftware,Internetarticles,andtutorials.Without
theircontributions,thisbook,andagreatdealelse,wouldnot
havebeenpossible.


WeWanttoHearfromYou!
Asthereaderofthisbook,youareourmostimportantcritic
andcommentator.Wevalueyouropinionandwanttoknow
whatwe'redoingright,whatwecoulddobetter,whatareas
you'dliketoseeuspublishin,andanyotherwordsofwisdom
you'rewillingtopassourway.

Youcanemailorwritemedirectlytoletmeknowwhatyoudid
ordidn'tlikeaboutthisbookaswellaswhatwecandotomake
ourbooksstronger.
PleasenotethatIcannothelpyouwithtechnicalproblems
relatedtothetopicofthisbook,andthatduetothehigh
volumeofmailIreceive,Imightnotbeabletoreplytoevery
message.
Whenyouwrite,pleasebesuretoincludethisbook'stitleand
authoraswellasyournameandphoneoremailaddress.Iwill
carefullyreviewyourcommentsandsharethemwiththeauthor
andeditorswhoworkedonthebook.

Email:



Mail:

MarkTaber
AssociatePublisher
SamsPublishing
800East96thStreet
Indianapolis,IN46240USA


ReaderServices
Visitourwebsiteandregisterthisbookat
www.samspublishing.com/registerforconvenientaccesstoany
updates,downloads,orerratathatmightbeavailableforthis
book.





Introduction
AjaxisstirringuphighlevelsofinterestintheInternet
developmentcommunity.Ajaxallowsdeveloperstoprovide
visitorstotheirwebsitesslick,intuitiveuserinterfaces
somewhatlikethoseofdesktopapplicationsinsteadofusing
thetraditionalpage-basedwebparadigm.
Basedonwell-knownandunderstoodtechnologiessuchas
JavaScriptandXML,Ajaxiseasilylearnedbythosefamiliarwith
themainstreamwebdesigntechnologiesanddoesnotrequire
userstohaveanybrowserplug-insorotherspecialsoftware.




AboutThisBook
PartoftheSamsPublishingTeachYourselfin10Minutesseries,
thisbookaimstoteachthebasicsofbuildingAjaxapplications
fortheInternet.Dividedintobite-sizedlessons,eachdesigned
totakenomorethanabout10minutestocomplete,this
volumeoffers
AreviewofthetechnologiesonwhichtheWorldWideWeb
isbased
Basictutorials/refreshersinHTML,JavaScript,PHP,andXML
AnunderstandingofthearchitectureofAjaxapplications
ExampleAjaxcodingprojects
Aftercompletingallthelessonsyou'llbeequippedtowriteand

understandbasicAjaxapplications,includingallnecessary
client-andserver-sideprogramming.




WhatIsAjax?
AjaxstandsforAsynchronousJavascriptAndXML.Although
strictlyspeakingAjaxitselfisnotatechnology,itmixeswellknownprogrammingtechniquesinanuncommonwaytoenable
webdeveloperstobuildInternetapplicationswithmuchmore
appealinguserinterfacesthanthosetowhichwehavebecome
accustomed.
Whenusingpopulardesktopapplications,weexpecttheresults
ofourworktobemadeavailableimmediately,withoutfuss,and
withoutushavingtowaitforthewholescreentoberedrawnby
theprogram.WhileusingaspreadsheetsuchasExcel,for
instance,weexpectthechangeswemakeinonecellto
propagateimmediatelythroughtheneighboringcellswhilewe
continuetotype,scrollthepage,orusethemouse.
Unfortunately,thissortofinteractionhasseldombeenavailable
tousersofweb-basedapplications.Muchmorecommonisthe
experienceofenteringdataintoformfields,clickingonabutton
orlink,andthensittingbackwhilethepageslowlyreloadsto
exhibittheresultsoftherequest.Inaddition,weoftenfindthat
themajorityofthereloadedpageconsistsofelementsthatare
identicaltothoseofthepreviouspageandthathavetherefore
beenreloadedunnecessarily;backgroundimages,logos,and
menusarefrequentoffenders.
Ajaxpromisesusasolutiontothisproblem.Byworkingasan
extralayerbetweentheuser'sbrowserandthewebserver,

Ajaxhandlesservercommunicationsinthebackground,
submittingserverrequestsandprocessingthereturneddata.
Theresultsmaythenbeintegratedseamlesslyintothepage
beingviewed,withoutthatpageneedingtoberefreshedora
newoneloaded.
InAjaxapplications,suchserverrequestsarenotnecessarily


synchronizedwithuseractionssuchasclickingonbuttonsor
links.Awell-writtenAjaxapplicationmayalreadyhaveaskedof
theserver,andreceived,thedatarequiredbytheuserperhaps
beforetheuserevenknewshewantedit.Thisisthemeaningof
theasynchronouspartoftheAjaxacronym.
ThepartsofanAjaxapplicationthathappen"underthehood"
oftheuser'sbrowser,suchassendingserverqueriesand
dealingwiththereturneddata,arewritteninJavaScript,and
XMLisanincreasinglypopularmeansofcodingandtransferring
formattedinformationusedbyAjaxtoefficientlytransferdata
betweenserverandclient.
We'lllookatallthesetechniques,andhowtheycanbemadeto
worktogether,asweworkthroughthelessons.


WhoThisBookIsFor
Thisvolumeisaimedprimarilyatwebdevelopersseekingto
buildbetterinterfacesfortheusersoftheirwebapplications
andprogrammersfromdesktopenvironmentslookingto
transfertheirapplicationstotheInternet.
Italsoprovesusefultowebdesignerseagertolearnhowthe
latesttechniquescanoffernewoutletsfortheircreativity.

AlthoughthenatureofAjaxapplicationsmeansthatthey
requiresomeprogramming,alltherequiredtechnologiesare
explainedfromfirstprincipleswithinthebook,soeventhose
withlittleornoprogrammingexperienceshouldbeableto
followthelessonswithoutagreatdealofdifficulty.


WhatDoINeedToUseThisBook?
Themainrequirementistohaveaninterestinexploringhow
peopleandcomputersmightworkbettertogether.Although
someprogrammingexperience,especiallyinJavaScript,will
certainlybeusefulitisbynomeansmandatorybecausethere
areintroductorytutorialsinalltherequiredtechnologies.
Totryouttheprogramcodeforyourselfyouneedaccesstoa
webserverandthemeanstouploadfilestoit(forexample,via
FileTransferProtocol,usuallycalledFTP).Makesurethatyour
webhostallowsyoutousePHPscriptsontheserver,though
themajoritydothesedays.
Towriteandeditprogramcodeyouneedasuitabletexteditor.
WindowsNotepaddoesthejobperfectlywell,thoughsome
specializedprogrammers'editorsofferadditionalusefulfacilities
suchaslinenumberingandsyntaxhighlighting.Theappendix
containsdetailsofsomeexcellentexamplesthatmaybe
downloadedandusedfreeofcharge.


ConventionsUsedinThisBook
Inadditiontothemaintextofeachlesson,youwillfinda
numberofboxeslabeledasTips,Notes,andCautions.


Tip
Tipsofferusefulshortcutsoreasierwaystoachievesomething.

Note
Notesaresnippetsofextrainformationrelevanttothecurrentthemeof
thetext.

Caution
Cautionsdetailtrapsthatmaycatchtheunwaryandadvisehowto
avoidthem.




OnlineResourcesandErrata
VisittheSamsPublishingwebsiteatwww.samspublishing.com
whereyoucandownloadtheexamplecodeandobtainfurther
informationanddetailsoferrata.


PartI:ARefresheronWebTechnologies
Lesson1.AnatomyofaWebsite
Lesson2.WritingWebPagesinHTML
Lesson3.SendingRequestsUsingHTTP
Lesson4.Client-SideCodingUsingJavaScript
Lesson5.Server-SideProgramminginPHP
Lesson6.ABriefIntroductiontoXML


Lesson1.AnatomyofaWebsite

Wehavealotofgroundtocoverinthisbook,solet'sgettoit.
We'llbeginbyreviewinginthislessonwhattheWorldWide
Webisandwhereitcamefrom.Afterwardwe'lltakealookat
someofthemajorcomponentsthatmakeitwork.




AShortHistoryoftheWeb
Inthelate1950s,theU.S.governmentformedtheAdvanced
ResearchProjectsAgency(ARPA).Thiswaslargelyaresponse
totheRussiansuccessinlaunchingtheSputniksatelliteand
employedsomeofthecountry'stopscientificintellectsin
researchworkwithU.S.militaryapplications.
Duringthe1960s,theagencycreatedadecentralizedcomputer
networkknownasARPAnet.Thisembryonicnetworkinitially
linkedfourcomputerslocatedattheUniversityofCaliforniaat
LosAngeles,StanfordResearchInstitute,theUniversityof
CaliforniaatSantaBarbara,andtheUniversityofUtah,with
morenodesaddedintheearly1970s.
Thenetworkhadinitiallybeendesignedusingthethen-new
technologyofpacketswitchingandwasintendedasa
communicationsystemthatwouldremainfunctionalevenif
somenodesshouldbedestroyedbyanuclearattack.
Emailwasimplementedin1972,closelyfollowedbythetelnet
protocolforloggingontoremotecomputersandtheFile
TransferProtocol(FTP),enablingfiletransferbetween
computers.
Thisdevelopingnetworkwasenhancedfurtherinsubsequent
yearswithimprovementstomanyfacetsofitsprotocolsand

tools.However,itwasnotuntil1989whenTimBerners-Leeand
hiscolleaguesattheEuropeanparticlephysicslaboratoryCERN
(ConseilEuropéenpourleRechercheNucléaire)proposedthe
conceptoflinkingdocumentswithhypertextthatthenow
familiarWorldWideWebbegantotakeshape.Theyear1993
sawtheintroductionofMosaic,thefirstgraphicalwebbrowser
andforerunnerofthefamousNetscapeNavigator.
Theuseofhypertextpagesandhyperlinkshelpedtodefinethe


page-basedinterfacemodelthatwestillregardasthenormfor
webapplicationstoday.


×