加入VIP
  • 专属下载特权
  • 现金文档折扣购买
  • VIP免费专区
  • 千万文档免费下载

上传资料

关闭

关闭

关闭

封号提示

内容

首页 Head First Ajax

Head First Ajax.pdf

Head First Ajax

zfpan
2014-03-14 0人阅读 举报 0 0 暂无简介

简介:本文档为《Head First Ajaxpdf》,可适用于IT/计算机领域

tableofcontentsviTableofContents(Summary)TableofContents(therealthing)YourbrainonAjaxHereyouaretryingtolearnsomething,whilehereyourbrainisdoingyouafavorbymakingsurethelearningdoesn’tstickYourbrain’sthinking,“Betterleaveroomformoreimportantthings,likewhichwildanimalstoavoidandwhethernakedsnowboardingisabadidea”SohowdoyoutrickyourbrainintothinkingthatyourlifedependsonknowingAjaxIntroWhoisthisbookforxxWeknowwhatyou’rethinkingxxiMetacognitionxxiiiBendyourbrainintosubmissionxxvReadmexxviThetechnicalreviewteamxxviiiAcknowledgmentsxxixIntroxixUsingAjax:WebAppsforaNewGenerationDesigningAjaxApplications:ThinkingAjaxianJavascriptEvents:ReactingtoyourusersMultipleEventHandlers:Two’sCompanyAsynchronousApplications:It’sLikeRenewingYourDriver’sLicenseTheDocumentObjectModel:WebPageForestryManipulatingtheDOM:MyWishisYourCommandFrameworksandToolkits:TrustNoOneXMLRequestsandResponses:MoreThanWordsCanSayJSON:SONofJavaScriptFormsandValidation:SayWhatYouMeanttoSayPostRequests:Paranoia:It’sYourFriendiAppendixi:TopFiveTopicsWeDidn’tCoveriiAppendixii:UtilityFunctionstableofcontentsviiWebAppsforaNewGenerationusingajaxWebpages:theoldfashionedapproachWebpagesreinventedSowhatmakesapage“Ajax”Rob’sRock‘n’RollMemorabiliaAjaxandrock‘n’rollinstepsStep:ModifytheXHTMLStep:InitializetheJavaScriptStep:CreatearequestobjectStep:Gettheitem’sdetailsLet’swritethecodeforrequestinganitem’sdetailsAlwaysmakesureyouhavearequestobjectbeforeworkingwithitTherequestobjectisjustanobjectHey,serverwillyoucallmebackatdisplayDetails(),pleaseUsesend()tosendyourrequestTheserverusuallyreturnsdatatoAjaxrequestsAjaxisserveragnosticUseacallbackfunctiontoworkwithdatatheserverreturnsGettheserver’sresponsefromtherequestobject’sresponseTextpropertyGoodbyetraditionalwebappsTiredofwaitingaroundforyourpagetoreloadFrustratedbyclunkywebapplicationinterfacesIt’stimetogiveyourwebappsthatslick,responsivedesktopfeelAndhowdoyoudothatWithAjax,yourtickettobuildingInternetapplicationsthataremoreinteractive,moreresponsive,andeasiertouseSoskipyournapit’stimetoputsomepolishonyourwebappsIt’stimetogetridofunnecessaryandslowfullpagerefreshesforeverTheserveralwaysdoessomeprocessingandsendsbackdatasometimesHTML,sometimesjustrawinformationTheserverresponds,andthebrowserrunsyourcallbackfunctionthumbnailsjsfunctiongetDetails{}getDetails()displayDetails()WebServerrequestrequestgetDetailsphpOurJavaScriptcanusetheserver’sdatatoupdatejustpartofthepage,·P�GHVSHUDWH����EXW�,�FDQ·W�DIIRUG�D�PRUH�SRZHUIXO�VHUYHU�RU�D�WHDP�RI�ZHE�HSHUWV�AjaxpagesonlytalktotheserverwhentheyhavetoandonlyaboutwhattheserverknowstableofcontentsviiiMike’straditionalwebsitesucksLet’suseAjaxtosendregistrationrequestsASYNCHRONOUSLYUpdatetheregistrationpageEventHandlersExposedSetthewindowonloadeventhandlerPROGRAMMATICALLYCodeinyourJavaScriptoutsideoffunctionsrunswhenthescriptisreadWhathappenswhenAndontheserverSomepartsofyourAjaxdesignswillbethesameeverytimecreateRequest()isalwaysthesameCreatearequestobjectonmultiplebrowsersAjaxappdesigninvolvesboththewebpageANDtheserversideprogramTherequestobjectconnectsyourcodetothewebbrowserYoutalktothebrowser,nottheserverThebrowsercallsbackyourfunctionwiththeserver’sresponseShowtheAjaxregistrationpagetoMikeThewebformhasTWOwaystosendrequeststotheservernowLet’screateCSSclassesforeachstateoftheprocessingandchangetheCSSclasswithourJavaScriptChangesWedon’tneednostinkin’changes!Onlyallowregistrationwhenit’sappropriateThinkingAjaxiandesigningajaxapplicationsWelcometoAjaxappsit’sawholenewwebworldSoyou’vebuiltyourfirstAjaxapp,andyou’realreadythinkingabouthowtochangeallyourwebappstomakerequestsasynchronouslyButthat’snotallthereistoAjaxprogrammingYou’vegottothinkaboutyourapplicationsdifferentlyJustbecauseyou’remakingasynchronousrequests,doesn’tmeanyourapplicationisuserfriendlyIt’suptoyoutohelpyourusersavoidmakingmistakes,andthatmeansrethinkingyourentireapplication’sdesignInProgressUsernameisokayUsernameistakenThesubmitbuttonisdisabledYoucansubmitthepagenowThisgraphictellsyoutheusernameisokayWhenyouenterausername,thisinprogressgraphicshouldbedisplayedtableofcontentsixItallstartedwithadownwardfacingdogAjaxappsaremorethanthesumoftheirpartsHere’sMarcy’sXHTMLEventsarethekeytointeractivityConnecteventsonyourwebpagetoeventhandlersinyourJavaScriptUsewindowonloadeventtoinitializetheinteractivityonawebpageChangethoseleftsideimagestobeclickableUseyourXHTML’scontentandstructureAddthecodeforhideHint(),tooTabs:anoptical(andgraphical)illusionUseaforlooptocyclethroughtheimagesCSSclassesarethekey(again)Ummmbutthetabsaren’t<a>’s!ThisbrokeourJavaScript,too,didn’titUsearequestobjecttofetchtheclassdetailsfromtheserverTwofunctionschangingthesamepartofawebpageWhenyouneedtochangeimagesinyourscript,think“changeCSSclasses”LinksinXHTMLarerepresentedby<a>elementsWeneedafunctiontoshowanactivebuttonandhideabutton,tooReactingtoyourusersjavascripteventsSometimesyouneedyourcodetoreacttootherthingsgoingoninyourwebapplicationandthat’swhereeventscomeintothepictureAneventissomethingthathappensonyourpage,inthebrowser,orevenonawebserverButit’snotenoughtojustknowabouteventssometimesyouwanttorespondtothemBycreatingcode,andregisteringitasaneventhandler,youcangetthebrowsertorunyourhandlereverytimeaparticulareventoccursCombineeventsandhandlers,andyougetinteractivewebapplicationsBeginnerThisiswhereyoushouldstartifyou’renewtoyogaIntermediateWhenthebeginnercourseisn’tachallenge,trythisoneAdvancedVerychallenging!tableofcontentsxAneventcanhaveonlyoneeventhandlerattachedtoit(orsoitseems)EventhandlersarejustpropertiesApropertycanhaveonlyONEvalueAssignmultipleeventhandlerswithaddEventListener()ObjectscanhavemultipleeventhandlersassignedtoasingleeventinDOMLevelWhat’sgoingonwithInternetExplorerInternetExplorerusesatotallydifferenteventmodelattachEvent()andaddEventListener()arefunctionallyequivalentaddEventHandler()worksforALLapps,notjustMarcy’syogapageLet’supdateinitPage()touseournewutilityfunctionUseanalert()totroubleshootSowhatelsecouldbegoingwrongEventhandlersinIEareownedbyIE’seventframeworkattachEvent()andaddEventListener()supplyanotherargumenttoourhandlersWeneedtonametheEventargument,soourhandlerscanworkwithitYousaytarget,IsaysrcElementSohowdoweactuallyGETtheobjectthattriggeredtheeventTwo’scompanymultipleeventhandlersAsingleeventhandlerisn’talwaysenoughSometimesyou’vegotmorethanoneeventhandlerthatneedstobecalledbyaneventMaybeyou’vegotsomeeventspecificactions,aswellassomegenericcode,andstuffingeverythingintoasingleeventhandlerfunctionwon’tcutitOrmaybeyou’rejusttryingtobuildclean,reusablecode,andyou’vegottwobitsoffunctionalitytriggeredbythesameeventFortunately,wecanusesomeDOMLevelmethodstoassignmultiplehandlerfunctionstoasingleeventcurrentBtnonmouseover=showHintJavaScriptfile<aid=""advanced"id="advanced"href="#">XHTMLfile<a>elementid="advanced"title="advanced"onmouseover=showHintThe<a>objecthasproperties:anid,title,anhref,andanonmouseoverEachpropertyhasanameandavaluehref="#"tableofcontentsxiWhatdoesasynchronousreallymeanYou’vebeenbuildingasynchronousappsallalongButsometimesyoubarelyevennoticeSpeakingofmoreserversideprocessing(More)AsynchronyineasystepsWeneedtwopasswordfieldsanda<div>forthecoverimagesIfyouneednewbehavior,youprobablyneedaneweventhandlerfunctionWithONErequestobject,sendandreceiveONEasynchronousrequestAsynchronousrequestsdon’twaitonanythingincludingthemselves!Ifyou’remakingTWOseparaterequests,useTWOseparaterequestobjectsYoucan’tcountontheORDERINGofyourrequestsandresponsesAmonitorfunctionmonitorsyourapplicationfromOUTSIDEtheactionYoucallamonitorfunctionwhenactionMIGHTneedtobetakenStatusvariablesletmonitorsknowwhat’sgoingonAndnowforourlasttrickSynchronousrequestsblockALLYOURCODEfromdoinganythingUsesetInterval()toletJavaScriptrunyourprocess,insteadofyourowncodeIt’slikerenewingyourdriver’slicenseasynchronousapplicationsAreyoutiredofwaitingaroundDoyouhatelongdelaysYoucandosomethingaboutitwithasynchrony!You’vealreadybuiltacoupleofpagesthatmadeasynchronousrequeststotheservertoavoidmakingtheusersitaroundwaitingforapagerefreshInthischapter,we’lldiveevendeeperintothedetailsofbuildingasynchronousapplicationsYou’llfindoutwhatasynchronousreallymeans,learnhowtousemultipleasynchronousrequests,andevenbuildamonitorfunctiontokeepallthatasynchronyfromconfusingyouandyourusersAnasynchronousrequestforcolaH��XIXV��ZLOO�RX�JHW�PH�DQRWKHU�FROD"Likebefore,youmakearequesttoRufustoGETyouacolaExceptthistime,youtellhimhe’sanasynchronousdog,·P�JRQQD�DVN�IRU�D�SD�UDLVH��RUH�FKHZ�WRV�Onceagain,RufusgoesafteryourcolaButthistime,RufusisanASYNCHRONOUSdogBythetimeRufusgetsback,you’reonthethgreenPerfecttimeforabreak!Theresultisthesame:yougetyourcolaThedifferenceisthatyouweren’tcompletelystuckwhileyouwerewaitingforitAndthatmeansyoucandowhateveryouwantwhilehe’sgettingthecolaYou’renotstucklikeyouwerewhenhewassynchronoustableofcontentsxiiYoucanchangetheCONTENTofapageoryoucanchangetheSTRUCTUREofapageBrowsersusetheDocumentObjectModeltorepresentyourpageHere’stheXHTMLthatyouwriteandhere’swhatyourbrowserseesYourpageisasetofrelatedobjectsLet’susetheDOMtobuildadynamicappYoustartwithXHTMLappendChild()addsanewchildtoanodeYoucanlocateelementsbynameorbyidInterviewwithanewparentCanImovetheclickedtileYoucanmovearoundaDOMtreeusingFAMILYrelationshipsADOMtreehasnodesforEVERYTHINGinyourwebpageThenodeNameofatextnodeis“#text”DidIwinDidIwinButseriouslydidIwinWanted:easytoupdatewebpagesIt’stimetotakethingsintoyourownhandsandstartwritingcodethatupdatesyourwebpagesontheflyUsingtheDocumentObjectModel,yourpagescantakeonnewlife,respondingtousers’actions,andyoucanditchunnecessarypagereloadsforeverBythetimeyou’vefinishedthischapter,you’llbeabletofind,move,andupdatecontentvirtuallyanywhereonyourwebpageWebPageForestrythedocumentobjectmodeldocument<html><scriptsrc=”js”><imgsrc=”siteLogopng”><html>classeshtmlThedocumentobjectcontainsthestructureofyourpage,whichisdefinedinyourXHTMLThestyleandeventhecodeattachedtoyourstructureisalsorepresentedintheDOM#tabs{}yogacssschedulejstableofcontentsxiiiMywishisyourcommandSometimesyoujustneedalittlemindcontrolIt’sgreattoknowthatwebbrowsersturnyourXHTMLintoDOMtreesAndyoucandoalotbymovingaroundwithinthosetreesButrealpoweristakingcontrolofaDOMtreeandmakingthetreelooklikeyouwantittoSometimeswhatyoureallyneedistoaddanewelementandsometext,ortoremoveanelement,likean<img>,fromapagealtogetherYoucandoallofthatandmorewiththeDOM,andalongtheway,banishthattroublesomeinnerHTMLpropertyaltogetherTheresultCodethatcandomoretoapage,withouthavingtomixpresentationandstructureinwithyourJavaScriptmanipulatingtheDOMDOMWebvillePuzzlesthefranchiseWoggledoesn’tusetablecellsforthetilesThetilesintheXHTMLareCSSpositioned“Wedon’twantTOTALLYrandomletters”OurpresentationisALLinourCSSWeneedaneweventhandlerforhandlingtileclicksStartbuildingtheeventhandlerforeachtileclickWecanassignaneventhandlerinourrandomizeTiles()functionPropertyvaluesarejuststringsinJavaScriptWeneedtoaddcontentANDstructuretothe“currentWord”divUsetheDOMtochangeapage’sstructureUsecreateElement()tocreateaDOMelementYouhavetoTELLthebrowserwheretoputanynewDOMnodesyoucreateWeneedtodisableeachtileThatmeanschangingthetile’sCSSclassANDturningOFFtheaddLetter()eventhandlerSubmittingawordisjust(another)requestOurJavaScriptdoesn’tcarehowtheserverfiguresoutitsresponsetoourrequestUsabilitycheck:WHENcansubmitWord()getcalledThegamestartsoutbycreatingabygridoflettersThelettersshouldberandomeachtimePlayerscanclicklettersto“build”wordsinthiswordpanePlayerscansubmitthewordtoseeifit’svalidandgetascorefortheword:pointforvowels,pointsforconsonantsAtilecanonlybeusedasingletimeineachwordOncethetile’sused,itshouldn’tbeselectableuntilanewwordisstartedUsedwordsgetaddedtothisboxtableofcontentsxivSowhatframeworksAREthereEveryframeworkusesadifferentsyntaxtodothingsThesyntaxmaychangebuttheJavaScriptisstillthesameToframeworkornottoframeworkThechoiceisuptoyouSowhat’stherealstorybehindallthoseAjaxframeworksIfyou’vebeeninWebvilleawhile,you’veprobablyrunacrossatleastoneJavaScriptorAjaxframeworkSomeframeworksgiveyouconveniencemethodsforworkingwiththeDOMOthersmakevalidationandsendingrequestssimpleStillotherscomewithlibrariesofprepackagedJavaScriptscreeneffectsButwhichoneshouldyouuseAndhowdoyouknowwhat’sreallygoingoninsidethatframeworkIt’stimetodomorethanuseotherpeople’scodeit’stimetotakecontrolofyourapplicationsTrustNoOneframeworksandtoolkitsClassicrockgetsastcenturymakeoverHowshouldaserversendaMULTIvaluedresponseinnerHTMLisonlysimplefortheCLIENTsideofawebappYouusetheDOMtoworkwithXML,justlikeyoudidwithXHTMLXMLisselfdescribingMoreThanWordsCanSayxmlrequestsandresponsesReasonstouseaframeworkReasonsNOTtouseaframeworkHowwillyoudescribeyourselfinyearsHowaboutSometimesyouneeddatathatcanchangewithyourneedsortheneedsofyourcustomersDatayou’reusingnowmightneedtochangeinafewhours,orafewdays,orafewmonthsWithXML,theextensiblemarkuplanguage,yourdatacandescribeitselfThatmeansyourscriptswon’tbefilledwithifs,elses,andswitchesInstead,youcanusethedescriptionsthatXMLprovidesaboutitselftofigureouthowtousethedatatheXMLcontainsTheresult:moreflexibilityandeasierdatahandlingRobwantstoaddapriceforeachitemEachitemwillhaveoneormoreURLstofindoutmoreabouttheitemtableofcontentsxvSONofJavaScriptjsonJavaScript,objects,andnotation,ohmy!IfyoueverneedtorepresentobjectsinyourJavaScript,thenyou’regoingtoloveJSON,JavaScriptStandardObjectNotationWithJSON,youcanrepresentcomplexobjectsandmappingswithtextandafewcurlybracesEvenbetter,youcansendandreceiveJSONfromotherlanguages,likePHP,C#,Python,andRubyJSONcanbetextANDanobjectJSONdatacanbetreatedasaJavaScriptobjectSohowdowegetJSONdatafromtheserver’sresponseJavaScriptcanevaluatetextualdataUseeval()tomanuallyevaluatetextEvaluatingJSONdatareturnsanobjectrepresentationofthatdataJavaScriptobjectsarealreadydynamicbecausethey’renotcompiledobjectsAccessanobject’smembers,thengetanobject’svalueswiththosemembersYouneedtoPARSEtheserver’sresponse,notjustEVALUATEitWebserverCSVWebserverXMLitemDetails=responsesplit(",")responseDoc=requestresponseXMLWebserverJSONdescription=itemdescriptiontableofcontentsxviformsandvalidationValidationshouldworkfromthewebpageBACKtotheserverYoucanvalidatetheFORMATandCONTENTofdataDon’tRepeatYourself:DRYLet’sbuildsomemoreeventhandlersRETURNofSONofJavaScriptThevalueofapropertycanbeanotherJavaScriptobjectLet’swarnMarcy’scustomerswhenthere’saproblemwiththeirentryIfyoudon’twarn(),youhavetounwarn()IFthere’sawarning,getridofitDuplicatedataisaSERVERproblemEveryonemakesmistakesfromtimetotimeGiveahumanbeingachancetotalk(ortype)forafewminutes,andthey’llprobablymakeatleastoneortwomistakesSohowdoyourwebappsrespondtothosemistakesYou’vegottovalidateyourusers’inputandreactwhenthatinputhasproblemsButwhodoeswhatWhatshouldyourwebpagedoWhatshouldyourJavaScriptdoAndwhat’stheroleoftheserverinvalidationanddataintegritySaywhatyoumeanttosayWebpageJavaScriptServerenrolljsrequestWebServertableofcontentsxviiGETrequestssendrequestparametersacrossthenetworkascleartextPOSTrequestsDON’TsendcleartextThedatainaPOSTrequestisENCODEDuntilitreachestheserversend()yourrequestdatainaPOSTrequestAlwayschecktomakesureyourrequestdatawasRECEIVEDWhydidn’tthePOSTrequestworkTheserverunencodesPOSTdataWeneedtoTELLtheserverwhatwe’resendingSetarequestheaderusingsetRequestHeader()onyourrequestobjectSomeone’swatchingyouRightnowSeriouslyFreedomofInformationActIsn’tthatcalledtheInternetThesedays,anythingausertypesintoaformorclicksonawebpageissubjecttoinspectionWhethe

用户评价(0)

关闭

新课改视野下建构高中语文教学实验成果报告(32KB)

抱歉,积分不足下载失败,请稍后再试!

提示

试读已结束,如需要继续阅读或者下载,敬请购买!

文档小程序码

使用微信“扫一扫”扫码寻找文档

1

打开微信

2

扫描小程序码

3

发布寻找信息

4

等待寻找结果

我知道了
评分:

/49

Head First Ajax

仅供在线阅读

VIP

在线
客服

免费
邮箱

爱问共享资料服务号

扫描关注领取更多福利