"Ajax" AJAX Implementation search information automatically recommended and complete

Source: Internet
Author: User

long time no continue to see the Ajax video tutorial, today will be the last tutorial case finished. When we enter text in the Search engine text box will prompt the corresponding information, this case is to achieve this basic function, the code is more rough also need to be further improved, some places also need to ask the great God. Finish the effect:


First, the pre-code preparation work:

1. Jqueryautocomplete.html is responsible for the display of the page side

A) as follows:

b) The code is as follows:

<! DOCTYPE html> 
    

c) Note: The page-side HTML code is basically not changed in the subsequent writing.

2. Jqueryauto.js is responsible for making changes to page elements

3. wordxml.jsp stored information recommended XML data

a)       initial code as follows (need to be modified later):

<!--this JSP returns the XML data, the ContentType value is Text/xml--><%@ Pagelanguage= "java" contenttype= "text/xml; Charset=utf-8 "pageencoding=" Utf-8 "%><!--return XML data, return all data, wait for the background to fully collaborate before restricting the return of content--><words> <WORD&G t;absolute</word> <word>anyone</word> <word>anything</word> <word>apple<     ;/word> <word>abandon</word> <word>breach</word> <word>break</word> <word>boolean</word></words> 

4. Autocomplete.java background servlet

A) The initial code is as follows (for simplicity, the servlet does not make a judgment operation, so there is basically no change in the following):

Import java.io.ioexception;importjavax.servlet.requestdispatcher;importjavax.servlet.servletexception; Importjavax.servlet.http.httpservlet;importjavax.servlet.http.httpservletrequest; importjavax.servlet.http.httpservletresponse;/** * @author Ginger * Full content Background code * Receive user requests */public class Autocompleteextends HttpServlet {     @Override     protected void doget (HttpServletRequest req, Httpservletresponseresp)                   throws Servletexception, IOException {            string word=req.getparameter ("word");//          Save the string in the Request object            Req.setattribute ("word", word);//          request forwarded to the view layer            requestdispatchertemp=req.getrequestdispatcher ("wordxml.jsp" );            Temp.forward (req, resp);     }      @Override     protected void DoPost (HttpServletRequest req,httpservletresponse resp)                   throws Servletexception, IOException {            doget (req, resp);}     }


Ii. Next we write the jqueryauto.js

1.   to set the style of the recommended text popup auto:

2.   Set button click events:

3.    Add keyboard events to the input text box

A) keyboard events are processed when you press the letter key, the up and down keys, and the ENTER key:

I. Letter key: Submitting text box data to the background

II. Key: Set the effect of the recommended text is highlighted

III. Enter: The effect of the analog button being clicked

4. Final code

Represents the currently highlighted node Var highlightindex=-1;$ (document). Ready (function () {////type var wordinput=$ ("#word") to set the pop-up box based on the input box;      var wordinputoffset=wordinput.offset (); Hide auto-complete div box $ ("#auto"). Hide (). CSS ("Border", "1pxblack solid"). CSS ("position", "absolute"). CSS ("Top",     Wordinput.height () +wordinputoffset.top+ "px"). CSS ("left", wordinputoffset.left+ "px"). Width (wordinput.width ()); Add a keyboard for the text box to press and bounce the event $ ("#word"). KeyUp (Event) {//Handling keyboard events in a text box//If you enter letters, BACKSPACE, delete keys, send information to server Var myevent=event | |      window.event;      var Keycode=myevent.keycode; if (keycode>=65&&keycode<=90 | | keycode==8 | |      KEYCODE==46) {//1. First get the text box contents var wordtext=$ ("#word"). Val ();                    2. Send the content to the server (when the text is not empty) var autonode=$ ("#auto");                   if (wordtext!= "") {$.post ("AutoComplete", {word:wordtext},function (data) {//                       2.1 Convert DOM object to jquery Object           var jqueryobj=$ (data);             2.2 Find all Word nodes varwordnodes=jqueryobj.find ("word");                                  2.3 Iterate through all word nodes, remove the word contents, add to Auto popup box//Empty the Fill box data before each commit data                                  Autonode.html (""); $ (wordnodes). Each (function (i) {//Get Word content var wordnode=$ (this);//Add a node to the pop-up box Autonode.append ($                                  ("<div>"). HTML (Wordnode.text ()));                                  });                                  if (Wordnodes.length >0) {autonode.show ();                                  }else{autonode.hide ();           }}, "xml");         }else{autonode.hide ();//Hide pop-up box and reset highlight value                    Highlightindex=-1;                  }}else if (keycode==38 | | keycode==40) {//if the input up and down buttons, then the complete content will be selected if (keycode==38) {//Up//                    Locate all child nodes of the current completion box varautonodes=$ ("#auto"). Children ("div"); if (highlightindex!=-1) {//If the original highlighted node is present, change the background to white Autonodes.eq (Highlightinde                           x). CSS ("Background-color", "White"). CSS ("Color", "black");                    highlightindex--;                    }else{highlightindex=autonodes.length-1;                           if (highlightindex==-1) {///If index is changed to 1 after the indexed value is modified, the index value is pointed to the last element                    Highlightindex=autonodes.length-1; } autonodes.eq (Highlightindex). CSS ("Background-color", "Blue"). CSS ("Color", "White "); } if (keycode==40) {//down//Find all child nodes of the current complement box varautonodes=$ ("#                    Auto "). Children (" div "); if (highlightindex!=-1) {//If the original highlighted node is present, change the background to white Autonodes.eq (Highlightinde                    x). CSS ("Background-color", "White"). CSS ("Color", "black");                    } highlightindex++;                           if (highlightindex==autonodes.length) {//If index is changed to 1 after the indexed value is modified, the index value is pointed to the last element                    highlightindex=0;             } autonodes.eq (Highlightindex). CSS ("Background-color", "Blue"). CSS ("Color", "white");                    }}else if (keycode==13) {//if the input Enter//Fill box has the selection if (highlightindex!=-1) {      varautonodes=$ ("#auto"). Children ("div");           Assigns the highlighted text to the input box $ ("#word"). Val (Autonodes.eq (Highlightindex). text ());         Highlightindex=-1;                    $ ("#auto"). Hide (); Alert ("Committed.             "); The}else{//Fill box does not have the selection alert ("committed.                    ");             $ ("#auto"). Hide (); }});//Add Click event $ ("input[type= ' button") for the button. Click (function () {alert ("committed.      "); })});


Third, finally in the background to filter the data

The final wordxml.jsp code is

<!--This JSP returns the XML data, the value of ContentType is Text/xml--><%@ pagelanguage= "java" contenttype= "text/xml; Charset=utf-8 "pageencoding=" Utf-8 "%><!--return XML data, return all data, wait for the background to fully collaborate, and then limit the return of the content--><% String word= (strin g) Request.getattribute ("word");%><words> <% if ("absolute". StartsWith (Word)) {%> <word>absol      Ute</word> <%}%> <% if ("anyone". StartsWith (Word)) {%> <word>anyone</word>      <%}%> <% if ("Anything". StartsWith (Word)) {%> <word>anything</word> <%}%> <% if ("Apple". StartsWith (Word)) {%> <word>apple</word> <%}%> <% if ("abandon". StartsWith (Word)) {%> <word>abandon</word> <%}%> <% if ("breach". StartsWith (Word)) { %> <word>breach</word> <%}%> <% if ("Break". StartsWith (Word)) {%> &LT;WORD&G T;break</word> <%}%> <% if ("Boolean". StartsWith (Word)) {%> <word>boolean</word> <%}%></words> 

Author: The beginning of the matter

Sign: As long as you're still trying. It doesn't count as failure.


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Ajax" AJAX Implementation search information automatically recommended and complete

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.