首页 > 代码库 > js模仿搜索引擎自动提示

js模仿搜索引擎自动提示

在文本框中随着输入的值显示相关的数据,类似于搜索引擎

测试数据放在xml文件中:

1,sourceInfo.xml

<?xml version="1.0" encoding="UTF-8"?><list>    <label id="a">        <content>abuse</content>        <content>abstract</content>        <content>accede</content>        <content>accelerate</content>        <content>accent</content>        <content>adverb</content>        <content>adverse</content>        <content>accent</content>        <content>accelerate</content>        <content>advance</content>        <content>affect</content>    </label>    <label id="b">        <content>bake</content>        <content>baggy</content>        <content>ball</content>        <content>band</content>        <content>bed</content>        <content>beck</content>    </label>    <label id="c">        <content>copy</content>        <content>condition</content>        <content>conduct</content>    </label></list>

2,jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>           <title>模仿搜索引擎      ---- maple 2014.09.08</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="http://www.mamicode.com/styles.css">    -->    <style type="text/css">                body{            width:800px;            margin:100px auto;        }        #rel{            position:absolute;            width:450px;            height:305px;            top:200px;            left:400px;                    }        #box{                        position:absolute;            width:560px;            height:50px;            top:150px;            left:400px;                    }                #txtContent{            border:1px solid green;            width:450px;            height:50px;            line-height:50px;            font-size:25px;            float:left;        }                a{            text-decoration:none;            width:110px;            height:50px;                        font-size:22px;            text-align:center;            font-weight:bold;            line-height:50px;            display:block;            color:white;            float:right;            background-color:#23AC3E;        }        ul{                        padding:0px;                        margin:0px;                    }        li{            padding-left:5px;            list-style:none;            font-size:25px;        }        .focus{            background-color:#efefef;        }        .myUl{            border:1px solid #ccc;        }    </style>    <script type="text/javascript" src="js/json2.js"></script>    <script type="text/javascript">    var txtContent; //保存文本框对象        var rel; //保存智能提示用的div对象    var ul; //无序列表对象,放每个提示信息    var focus; //按上下键时,保存当前选中项这个li对象        var JSONAjax={            xmlHttpreq : false,                            createXMLHttpReq : function() {  //创建XHR对象            if (window.XMLHttpRequest) {                // Mozilla                xmlHttpreq = new XMLHttpRequest();            } else {                // IE                if (window.ActiveXObject) {                    try {// 比较新的版本                        xmlHttpreq = new ActiveXObject("Msxml2.XMLHttp");                    } catch (e) {                        try {// 失败就创建比较老的版本                            xmlHttpreq = new ActiveXObject("Microsoft.XMLHttp");                        } catch (e) {                        // 还失败就回家种田                        }                    }                }//end of if            }//end of else        }, //end of create            //发送请求(核心!!!)        sendreq : function(value) {            url="ReminderServlet?content="+value;            //调用创建XMLREQ对象 的方法            JSONAjax.createXMLHttpReq();            //指定回调函数            xmlHttpreq.onreadystatechange= JSONAjax.handleResponse;            //建立连接            xmlHttpreq.open("GET", url, true); //异步传输            //发送数据            xmlHttpreq.send(null);        },                //处理响应         handleResponse:function() {        // 判断XHR的状态            if (xmlHttpreq.readyState == 4) {                                // 回应的状态=200,表示成功返回了服务器的内容                if (xmlHttpreq.status == 200) {                                        var str=xmlHttpreq.responseText;                                            var obj=JSON.parse(str);//解析成json对象                    var len=ul.childNodes.length;                                //移除ul原有项                            for(var j=0;j<len;j++){                                                ul.removeChild(ul.firstChild);                                            }                                            //规定最多显示10条提示信息                                    var count=obj.count>10?10:obj.count;                        //动态添加提示信息                                    for(var i=0;i<count;i++){                        var li=document.createElement("li");                                                var txt=document.createTextNode(obj["a"+i]);                        li.appendChild(txt);                        ul.appendChild(li);                    }                    //如果ul中有li项,则通过添加类样式来显示边框                    if(ul.childNodes.length>0){                        ul.className="myUl";                    }else{  //如果没有了提示项,则去除类样式                        ul.className="";                    }                }//end status==200            }//end readyState==4        }, //end handleResponse                //为组件添加事件:组件,要绑定的事件类型,处理事件的函数,是否捕获        addEvent: function(elm, evType, fn, useCapture){                    //支持火狐                    if (elm.addEventListener){                            elm.addEventListener(evType, fn, useCapture);                            return true;                    } else if (elm.attachEvent) {                    //支持IE                        var r = elm.attachEvent(on + evType, fn);                        return r;                    } else {                        elm[on + evType] = fn;                    }                },                        //初始化            init:function(){                txtContent=document.getElementById("txtContent");                rel=document.getElementById("rel");                                ul=document.createElement("ul");                                        rel.appendChild(ul);//显示提示信息的无序列表放在id=rel的div块中                focus=null;                                txtContent.onkeyup=function(event){                    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;                    if(keyCode==38){ //向上方向键                        //alert("up");                        if(focus!=null&&focus!=ul.childNodes[0]){                            focus.className="";                            focus=focus.previousSibling;                            focus.className="focus";                            //把方向键选择项的值放在文本框中                            txtContent.value=focus.textContent;                        }                                                return;                                            }else if(keyCode==40){ //向下                        //alert("down");                        if(focus==null){                            focus=ul.childNodes[0];                                                    }else if(focus==ul.lastChild){                                                        return;                        }else{                            focus.className="";                            focus=focus.nextSibling;                                                    }                                    txtContent.value=focus.textContent;                                    focus.className="focus";                                                return;                                                                    }else if(keyCode==13){  //回车                        window.location.href="http://www.baidu.com";                    }                                        JSONAjax.sendreq(this.value);                };            },                }; //end of JSONAjax                //初始化[相当于调用 了<body onl oad="fn"> ]    JSONAjax.addEvent(window,load,JSONAjax.init,false);        </script>  </head>    <body>          <div id="box">    <input type="text" name="txtContent" id="txtContent">   <a href="#">千寻一下</a>    </div>    <div id="rel">    </div>     </body></html>

3,servlet

package com.maple.servlet;import java.io.File;import java.io.IOException;import java.io.PrintWriter;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONObject;import org.jdom.Document;import org.jdom.Element;import org.jdom.JDOMException;import org.jdom.input.SAXBuilder;public class ReminderServlet extends HttpServlet {    /**     * Constructor of the object.     */    public ReminderServlet() {        super();    }        public void destroy() {        super.destroy(); // Just puts "destroy" string in log        // Put your code here    }        public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        response.setContentType("text/html");                PrintWriter out = response.getWriter();        //获取输入的文本内容        String content=request.getParameter("content");        SAXBuilder sax=new SAXBuilder();        File file=new File("E:\\myJava\\javafrom20140825\\myself\\assignment_mockbaidu\\src\\sourceInfo.xml");                try {            Document doc=sax.build(file);            Element root =doc.getRootElement(); //list            List labels=root.getChildren("label");            String id=null;                        //用于保存目标标签块,例如输入abu,则保存a标签块的内容            Element target=null;             JSONObject job=new JSONObject();                        //寻找与输入的首字母相同的标签块            for(int i=0;i<labels.size();i++){                id=((Element)(labels.get(i))).getAttributeValue("id");                if(content.indexOf(id)==0){                    target=(Element)(labels.get(i));                        break;                }            }            //如果找到了与首字母匹配的标签块            if(target!=null){                List con=target.getChildren("content");                int count=0;                for(int j=0;j<con.size();j++){                    Element temp=(Element)(con.get(j));                    String tempContent=temp.getText();                                                //如果content标签内的值与文本值前面相同,则保存在json对象中,                    //这是真正的有效值,需要回传给客户端                    if(tempContent.indexOf(content)!=-1){                                                job.put("a"+count, tempContent);                        ++count;                                            }                                                }                //最后加上有效键值对的个数,方便客户端读取                job.put("count", count);            }            out.print(job);                    } catch (JDOMException e) {                        e.printStackTrace();        }        out.flush();        out.close();    }        public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        doGet(request,response);    }        public void init() throws ServletException {        // Put your code here    }}

 

js模仿搜索引擎自动提示