查看Demo
代码语言:javascript复制/**
* @author xiaohejun
* Man Always Remember Love Because of Romance Only.
*
*/
一.实现效果:
1.serach.jsp
代码语言:javascript复制<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>搜索</title>
<style type="text/css">
#myDiv {
position:absolute;
left: 50%;
top: 50%;
margin-left: -200px;
margin-top: -50px;
}
.mouseOver{
background: #708090;
color: #FFFAFA;
}
.mouseOut{
background: #FFFAFA;
color: #000000;
}
</style>
<script type="text/javascript">
var xmlHttp;
/*获得用户关联信息*/
function getMoreContents() {
// 首先获得用户输入
var content = document.getElementById("keyword");
if(content.value == ""){
return;
}
// 然后给服务器发送用户输入类容,用ajax异步发送请求,获得一个对象,骄傲做xmlHttp
xmlHttp = createXmlHttp();
// 要给服务器发送数据,escape()方法对字符串进行编码
var url="search?keyword=" decodeURI(content.value);
// 和服务器建立链接,true参数表示javascript脚本会在send()方法之后继续执行,而且不会等待来自服务器的响应
xmlHttp.open("GET",url);
// 绑定一个回调方法,这个会调方法会在xmlHttp状态改变0-4,我们只关心4(complete)这个状态,完成之后,调用回调方法
xmlHttp.onreadystatechange=callback;
xmlHttp.send(null);
}
// 清空之前的数据
function clearContent() {
var tbody = document.getElementById("content_table_body");
var size = tbody.childNodes.length;
for (var i = size-1; i >= 0;i--) {
tbody.removeChild(tbody.childNodes[i]);
}
document.getElementById("popDiv").style.border = "none";
}
//回调函数
function callback() {
if(xmlHttp.readyState==4){
// 服务器响应成功
if(xmlHttp.status==200){
// 交互成功,获得响应数据
var result = xmlHttp.responseText;
// 解析成JSON格式
var json = eval("(" result ")");
// 获得数据之后,就可以动态显示这些数据,把这些数据展示到输入框的下面
setContent(json);
}
}
}
// 设置关联数据的展示
function setContent(contents) {
clearContent();
setLocation();
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.bgColor = "white";
td.onmouseover = function () {
this.className = 'mouseOver';
};
td.onmouseout = function () {
this.className = 'mouseOut';
}
td.onmousedown = function() {
document.getElementById("keyword").value = this.innerHTML;
}
var text = document.createTextNode(nextNode);
td.appendChild(text);
tr.appendChild(td);
document.getElementById('content_table_body').appendChild(tr);
}
}
// 获得xmlHttp对象
function createXmlHttp() {
// 对于大多数浏览器适用的
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
// 要考虑浏览器的兼容
if (window.ActiveXObiect) {
xmlHttp = new ActiveXObiect("Microsoft.XMLHTTP");
if (!xmlHttp) {
xmlHttp = new ActiveXObiect("Msxml2.XMLHTTP");
}
}
return xmlHttp;
}
function keywordBlur() {
clearContent();
}
// 设置显示的位置
function setLocation() {
// 关联信息的显示位置要和输入框一致
var content = document.getElementById("keyword");
// 输入框的宽度
var width = content.offsetWidth;
// 到左边框的距离
var left = content["offsetLeft"];
// 到顶部的距离
var top = content["offsetTop"] content.offsetHeight;
// 获得显示数据的div
var popDiv = document.getElementById("popDiv");
popDiv.style.border = "black 1px solid";
popDiv.style.left = left "px";
popDiv.style.top = top "px";
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="keyword" onkeyup="getMoreContents()" onblur="keywordBlur()" onfocus="getMoreContents()"/>
<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>
2.SearchServlet.java
代码语言:javascript复制package com.servlet;
import java.io.IOException;
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 search
*/
@WebServlet("/search")
public class SearchServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static List<String> datas;
/**
* @see HttpServlet#HttpServlet()
*/
public SearchServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
static {
datas = new ArrayList<String>();
datas.add("ajax");
datas.add("ajax post");
datas.add("b啊哈");
datas.add("b哈");
datas.add("这是ajax");
datas.add("你全家都是ajax");
}
public List<String> getData(String keyword) {
List<String> list = new ArrayList<String>();
for (String data : datas) {
if (data.contains(keyword)) {
list.add(data);
}
}
return list;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");;
String keyword = request.getParameter("keyword");
List<String> listData = getData(keyword);
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);
}
}
注意:不可以使用escape()函数编码,已经过时