搜索框智能提示小Demo

前言

感谢这个大牛的视频:

 http://www.imooc.com/wap/learn/?id=678&from=singlemessage  

效果图


代码:

前端代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="path" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title her</title>
<style type="text/css">
#mydiv{
	position: absolute;
	left:50%;
	top:50%;
 	margin-top:-50px; 
 	margin-left:-200px; 
}

.mouseOver{
	background:#708090;
	color:#FFFAFA;
}
.mouserOut{
	background:#FFFAFA;
	color:#000000;
}
</style>
<script type="text/javascript">

	function getMoreContents(){
		//获取用户的输入
		clearContent();
		
		var content = document.getElementById("searchword");
		if(content.value==""){
			return ;
		}
		//用XMlHttp对象来完成Ajax异步加载
		setLocation();
		xmlHttp=createXMLHttp();
		var url="${path}/search?searchWord="+content.value;
		xmlHttp.open("GET",url,true);
		xmlHttp.onreadystatechange=callback;
		xmlHttp.send(null);
	}
	
	function createXMLHttp(){ //新建xmlHttp
		var xmlHttp;
		if(window.XMLHttpRequest){  //大多数都支持的
			xmlHttp= new XMLHttpRequest();
		}
		if(window.ActiveXObject){   //考虑ie,其中ActiveXObject 为创建或启动自动化对象
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); //高版本ie
			if(!xmlHttp){
				xmlHttp= new ActiveXObject("Msxml2.XMLHTTP"); //低版本Ie
			}
		}
		return xmlHttp;
	}
	function callback(){  监控xml状态的并做出改变的函数
		if(xmlHttp.readyState==4){ //请求完成
			if(xmlHttp.status==200){  //访问成功
				var result=xmlHttp.responseText;
				var json=eval("("+result+")");  //解析为json格式
				setContents(json);
			}
		}
		
	}
	function setContents(contents){  //生成相似词语组
// 		clearContent();
		var size= contents.length;
		for(var i=0;i<size;i++){
			var nextNode=contents[i];
			var tr=document.createElement("tr");
			var td=document.createElement("td");
			td.setAttribute("border","0");
			td.setAttribute("bgcolor","#FFFAFA");
			td.οnmοuseοver=function(){
				this.className='mouseOver';
			};
			td.οnmοuseοut=function(){
				this.className='mouseOut';
			};
			td.οnmοusedοwn=function(){
				document.getElementById("searchword").value=this.innerText;
			};
			var text= document.createTextNode(nextNode);
			td.appendChild(text);
			tr.appendChild(td);
			document.getElementById("content_table_body").appendChild(tr);	
		}
	}
	function searchWordBlur(){  //输入框失去焦点
		clearContent();
	}
	function searchWordFocus(){  //输入框获得焦点
		getMoreContents();
	}
	
	function clearContent(){
		var contentTable=document.getElementById("content_table_body");
		var size=contentTable.childNodes.length;
		for(var i=size-1;i>=0;i--){
			contentTable.removeChild(contentTable.childNodes[i]);
		}
		document.getElementById("popDiv").style.border="none";
		
	}
	function setLocation(){   //显示框的长度调整
		var content=document.getElementById("searchword");
		var width=content.offsetWidth;
		popDiv.style.border="black 1px solid";
 		popDiv.style.width=width+"px";
		document.getElementById("content_table").style.width=width+"px";
	}
</script>
</head>
<body>
<div id = "mydiv">
	<!-- 输入框 -->
	<input type="text" size="50" id="searchword" οnkeyup="getMoreContents()"
	οnblur="searchWordBlur()" οnfοcus="searchWordFocus()"/>
	<input type="button" value="百度一下" width="50px" />
	<div id="popDiv">
		<table id="content_table" bgcolor="#FFFAFA" border="0" cellspacing="0"
		cellpadding="0">
		<tbody id="content_table_body">
		
		</tbody>
		</table>
	</div>
</div>
</body>
</html>

后端代码
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

/**
 * Servlet implementation class SearchServlet
 */
@WebServlet("/search")
public class SearchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
	static List<String> datas=new ArrayList<String>();
	static{
		datas.add("中国");
		datas.add("中间");
		datas.add("bb1");
		datas.add("bb2");
		datas.add("bb3");
		datas.add("bb4");
	}
    public SearchServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");


		String searchWord=new String (request.getParameter("searchWord").getBytes("ISO-8859-1"),"UTF-8");
//		String searchWord=URLDecoder.decode(request.getParameter("searchWord"),"utf-8");
		System.out.println(searchWord);
		List<String> listData=getData(searchWord);
		response.getWriter().write(JSONArray.fromObject(listData).toString());

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	
	public List<String> getData(String searchWord){
		List<String> list=new ArrayList<String>();
		for(String data:datas){
			if(data.contains(searchWord)){
				list.add(data);
			}
		}
		return list;
	}
}


总结

其实这篇重点有点不照题了,全视频其实就是在讲原生的ajax的实现,智能提示也只是静态的,个人觉得作者应多多放在关联词的生成,数据库怎么实现,从而形成真正意义上类似百度那样强大的搜索,不过总体还是不错的!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值