Tải bản đầy đủ - 0 (trang)
Hack 89. Get Related Terms Instantly with Ajax

Hack 89. Get Related Terms Instantly with Ajax

Tải bản đầy đủ - 0trang

ThishackisasimpleAjaxapplicationthatusesYahoo!Web

Servicesasadatasource.AsyoutypeinstandardHTMLtext

input,JavaScriptisinconstantcommunicationwiththeYahoo!

API.Witheveryletteradded,thescriptcheckstoseeifYahoo!

hasrelatedsearchsuggestionsforthecurrentsearchterm.

Relatedsearchsuggestionsaresimplyphrasesthatarerelated

toanyquery,andthey'redisplayedbelowthetextinputasyou

type.Thisway,ifyou'retypingactiveXcontrolintotheform,you

canseesuggestedalternatetermslikeactivevolcanoesandfree

activeXalongtheway.



5.14.1.TheCode

ThisscriptreliesontheXMLHTTPobjecttosendandreceive



responsesfromaserver,andtoparsethoseresponsesinto

objectsthatJavaScriptcanmanipulate.Whenthepageloads,

anXMLHTTPobjectiscreated.Theuser-inputtextfieldhasan

onkeyupevent,sothatwhentheuser'sinputhasakeystroke,the

getAlts()functioncontactstheYahoo!SearchWebServices,

lookingforrelatedsearchterms.Iftherearenorelatedterms,

nothinghappens.Ifrelatedtermsarefound,theprintResponse()

functionformatstherelatedsearchtermsasHTMLandprints

themtothepagewiththeinnerHTMLpropertyofa
tagbelow

theform.

ThiscodeisastandardHTMLfile,anditdoesn'tneedtoreside

onawebserver.Simplyopenatexteditor,suchasNotepad,

addthefollowingcode,andnamethefilerelatedterms.html:




































































































enablePrivilege("UniversalBrowserAccess");



varxmlhttp=false;



/*@cc_on@*/



/*@if(@_jscript_version>=5)



//Verifythatthebrowsercanloadthe



try{



xmlhttp=newActiveXObject("Msxml2.X



}catch(e){



try{



xmlhttp=newActiveXObject("Microso



}catch(E){



xmlhttp=false;



}



}



RelatedTerms


//netscape.security.PrivilegeManager.

































@end@*/

if(!xmlhttp&&typeofXMLHttpRequest!=

xmlhttp=newXMLHttpRequest();

}













































//Acceptsarelatedterm,andmakesit

functiongetLink(r){



varo="


o=o+escape(r)+"\">"+r+



returno;

}

































//AcceptstheYahoo!SearchWebServic

//printstothepageasHTML

functionprintResponse(xml){

//netscape.security.PrivilegeManager



































enablePrivilege("UniversalXPConnect");



varresults=xml.getElementsByTagNam



varnumOfResults=results.length;



if(numOfResults>0){



varout="";



for(vari=0;i




out=out+"
  • "+getLink(re



    "
  • ";



















    }











    }

    vars=document.getElementById('suggest');

    s.innerHTML="Youmightalsotry:
      "+out+

      }



      //Acceptsafullorpartialsearchterm,andlooksf

      //relatedtermswithaYahoo!SearchWebServicesre

      functiongetAlts(t){



      varyurl="http://api.search.yahoo.com/WebSe











      yurl=yurl+"relatedSuggestion?appid=





      escape(t);



      //netscape.security.PrivilegeManager.





      enablePrivilege("UniversalXPConnect");





      try{







      xmlhttp.open("GET",yurl,true);





      }





      catch(E){







      alert(E);





      }





      xmlhttp.onreadystatechange=function(){







      if(xmlhttp.readyState==4){









      printResponse(xmlhttp.responseX







      }







      }







      xmlhttp.send(null)





      }













      Yahoo!RelatedTerms




















    Asyoucansee,theHTMLforthispageisstraightforward,and

    theworkisdoneintheJavaScriptsectionintheofthe

    page.BesuretorequestauniqueapplicationIDforthescript



    anduseitinthecode.



    5.14.2.RunningtheHack

    Toavoidpotentialproblemswithcross-sitescriptingexploits,by

    defaultbrowsersdonotallowJavaScripttocallpagesfrom

    otherdomains.AndbecauseYahoo!SearchWebServicesareat

    anotherdomain,thisscriptwillrequiresomebrowsertweaksto

    run.Ifyouweretoimplementthisscriptonawebsite,you'd

    needtosetthisupinadifferentway.Butthisexampleis

    intendedtoshowwhat'spossiblewithAjax,ratherthanthe

    perfectwaytodeployanAjaxapplicationtootherusers.

    WhenyouopenthispageinInternetExplorer,you'llprobably

    seeayellowsecuritywarningliketheoneshownbelowthe

    AddressbarinFigure5-29.



    Figure5-29.InternetExplorersecuritywarning



    Clicktheyellowbanner,andchooseAllowBlockedContent…to

    letthescriptcontactYahoo!.

    ForFirefox,you'llneedtouncommentthefollowingtextby



    removingthedoubleslashesatthebeginningofitslinein

    relatedterms.html:



    netscape.security.PrivilegeManager.enablePrivilege("UniversalXP



    Thiswillallowthebrowsertocontactaremotedomain,andthe

    firsttimeittriestorun,you'llseearequesttoallowthe

    privilegechange,asshowninFigure5-30.



    Figure5-30.Firefoxsecurityrequest



    Checkthe"Rememberthisdecision"boxandthenclickthe

    Allowbutton.Ifyoueverspotthisdialogwhilebrowsingafile

    thatyoudidn'twrite,you'llwanttoclickDenyinstead.But

    becauseyou'reincontroloftheinformationbeingpassed

    around,youcanbesureyou'renotdoinganythingmalicious.

    Withthesecuritysettingsbehindyou,youcanstartplaying

    withthescript.Asyoutype,theJavaScriptcontactsYahoo!for

    suggestions.TrysearchingforthetechtermactiveXComponent,

    andyou'llseedifferentsuggestionsappearalongtheway.After

    youtypethefirstsixletters(active),severalsuggestionsappear

    belowtheform,asshowninFigure5-31.



    Figure5-31.Yahoo!relatedtermsfor"active"



    Keeptyping,andnewsuggestionsappearasyoutypetheX,as

    showninFigure5-32.

    Clickanyofthesuggestionstoviewthesearchresultsforthat

    phraseatYahoo!.ThecompletephraseactiveXControlwillyield

    evenmoresuggestions.



    Hack90.ComparethePopularityofRelated

    SearchTerms



    BygluingtogethertwodifferentkindsofYahoo!Web

    Servicesrequests,youcanfindthemostwidelyused

    alternatesearchrequestsforanygiventopic.

    ThoughtheYahoo!Searchengineissomethingeachofususe

    inisolation,fromYahoo!'sperspectivesearchingisagroup

    activity.Theyhavetheabilitytoanalyzeeachindividualquery

    andgroupittogetherwithother,similarqueries.Whenyoudoa

    websearchonYahoo!,youcangetaglimpseofthesesimilar

    phrases.Figure5-33highlightsthelistof"Alsotry:"phrasesfor

    asearchonthetermrobot.

    Yahoo!hasalsoexposedsomeofthisgroupdataintheRelated

    SuggestionsfeatureofYahoo!SearchWebServices.



    Figure5-32.Yahoo!relatedtermsfor"activeX"



    Figure5-33."Alsotry:"relatedsuggestionon

    Yahoo!Searchresults



    Tài liệu bạn tìm kiếm đã sẵn sàng tải về

    Hack 89. Get Related Terms Instantly with Ajax

    Tải bản đầy đủ ngay(0 tr)

    ×