Servlet+Ajax实现百度智能搜索

2017-01-13 19:10:04来源:CSDN作者:qq_27905183人点击

通常在一个form表单的搜索输入框中我们输入想要搜索的数据时,无任何提示或者提示我们曾经输入过的数据,这并没有什么用处。我们可以看看诸如百度的搜索框,我们每次在输入框中输入数据时,都会在下面出现一个下拉列表,提示我们想要搜索的值,这些都是百度搜索引擎中从数据库里面读取出来的数据。现在我们实现一个模拟百度智能搜索的操作

1.建立前端模板    index.jsp<%@page language="java" contentType="text/html;charset=UTF-8" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>百度一下,你就知道</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="viewport" content="width=devide-width,initial-scale=1.0" />    <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="CSS/style.css" />    <script type="text/javascript" src="JS/search.js"></script>  </head>  <body>    <img src="Images/logo.png" title="百度一下" />    <form action="#" method="get">        <input type="text" name="inform" id="inform" placeholder="百度一下,你就知道" />        <button type="submit">百度一下</button>    </form>    <table id="content-table">        <tbody id="content-body">        </tbody>    </table>  </body></html>
2.编写简单的CSS布局效果  CSS/style.cssbody{padding: 0px;margin: 0px;}img{margin-left: 450px;margin-top: 10px;}form{position: absolute;left: 450px;top: 300px;}input{width: 540px;height: 35px;}input:hover{border: 1px solid grey;}button{width: 100px;height: 35px;background-color: rgb(51,133,255);margin-left: -10px; }button:hover{background-color: rgb(49,126,243);cursor: pointer;}table{margin-left: 450px;margin-top: 68px;border: 1px solid rgba(128,128,128,0.5); border-radius: 2px; width: 540px; height: 35px; visibility: hidden;}table  tr:hover{background-color: rgb(240,240,240); cursor: pointer;}
3.编写核心JS操作  JS/search.jswindow.onload = function(){    //1.获取输入的值    var content, inform;    function getSearchValue(){        inform = document.getElementById("inform");        content = inform.value;    };    getSearchValue();    //2.获取Ajax对象    var ajax = null;    function getAjaxObject(){        if(window.XMLHttpRequest)            return new XMLHttpRequest();        if(window.ActiveXObject)            return new ActiveXObject(Microsoft.XMLHTTP);        return new ActiveXObject(Msxml.XMLHTTP);    };    ajax = getAjaxObject();    //3.定义输入框的keyup事件    var table = document.getElementById("content-table");    var tbody = document.getElementById("content-body");    inform.onkeyup = function(){        getSearchValue();        if(content == ""){            tbody.innerHTML = "";            table.style.visibility = "hidden";            return ;        }        //4.发送Ajax异步请求        var url = "search?keyword="+encodeURI(encodeURI(content));        ajax.open("GET", url, true);        //5.获得服务器返回的JSON数据        ajax.onreadystatechange = function(){            if((ajax.readyState == 4 && ajax.status == 200)){                var result = ajax.responseText;                //解析获得的json数据                var json = eval("(" + result + ")");                //6.对传回来的数据进行table显示                showData(json);            }        };        ajax.send(null);    };    //显示传回来的json数据    function showData(json){        var length = json.length;        tbody.innerHTML = "";        if(length == 0){            table.style.visibility = "hidden";            return;        }        table.style.visibility = "visible";        for(var i=0; i<length; i++){            var tr = document.createElement("tr");            var td = document.createElement("td");            var text = document.createTextNode(json[i]);                        td.appendChild(text);            tr.appendChild(td);            tbody.appendChild(tr);              }    };    //7.当输入框失去焦点时隐藏提示框    inform.onblur = function(){        table.style.visibility = "hidden";          };    //8.当输入框重新获得焦点时如果之前提示框有数据则继续显示    inform.onclick = function(){        if(tbody.innerHTML == "" || table.rows.length == 0)            return ;        table.style.visibility = "visible";    };  };
4.编写Servlet处理ajax响应 com.imooc.SearchServletpackage com.imooc;import java.io.IOException;import java.net.URLDecoder;import java.util.ArrayList;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.JSONArray;public class SearchServlet extends HttpServlet {    private static final long serialVersionUID = 1L;    //事先定义静态数据模拟数据库操作    private static List<String> datas = new ArrayList<String>() ;    static{        datas.add("ajax api");        datas.add("ajax编程中文版");        datas.add("ajax教程");        datas.add("轩辕剑之天之痕");        datas.add("天上人间");        datas.add("从此有你不寒冷");        datas.add("孤芳不自赏");        datas.add("中国传媒大学");        datas.add("湖南工业大学");        datas.add("陈思诚出轨");        datas.add("当红小鲜肉");        datas.add("当浪漫也是一种罪");        datas.add("回家的诱惑");        datas.add("UFO的由来");    }    @Override    protected void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        //进行数据编码        request.setCharacterEncoding("utf-8");        response.setCharacterEncoding("utf-8");        String keyword = request.getParameter("keyword");        keyword = URLDecoder.decode(keyword, "utf-8");        String result[] = new String[5];        int index = 0;        //与datas集合对象模拟数据库检索        for(String data: datas){            if(data.indexOf(keyword) < 0)                continue ;            result[index++] = data;            if(index == 5)                break;        }        String data[] = new String[index];        for(int i=0; i<index; i++){            data[i] = result[i];        }        //将JSON数据传回给浏览器    response.getWriter().write(JSONArray.fromObject(data).toString());    }}
5.在web.xml配置文件中配置Servlet web.xml  <!-- 配置Servlet -->  <servlet>    <servlet-name>search</servlet-name>    <servlet-class>com.imooc.SearchServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>search</servlet-name>    <url-pattern>/search</url-pattern>  </servlet-mapping>

实现效果图:
这里写图片描述

这里写图片描述

参考出处:慕课网->Servlet+Ajax实现智能化搜索视频教程

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台