模仿google自动补全代码
1、autocompleteserver代码
复制代码 代码示例:
package com.web;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AutoCompleteServer extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取从页面传递过来的参数
String word=request.getParameter("word");
System.out.println("AutoComplete");
//将字符串保存到request对象中
request.setAttribute("word", word);
//将请求转发给视图层
request.getRequestDispatcher("/keyWord.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
2、autoComplete.js页面
复制代码 代码示例:
$(document).ready(function(){
//自动补全框开始隐藏起来
$("#auto").hide().css("border","1px red solid");
//给
文本框注册键盘按下弹起事件
$("#word").keyup(function(){
//处理文本框中键盘事件
//首先,获取文本框中的内容
var wordText=$("#word").val();
//将文本框中的内容发送给
服务器
$.post("servlet/AutoCompleteServer",{word:wordText},function(data){
//将dom对象data转换成
jquery的对象
var jqueryObj=$(data);
//找到autoComplete.jsp所有的word节点
var wordNodes=jqueryObj.find("word");
//遍历所有的word节点,取出单词内容,然后将单词内容添加到弹出框中
var autoNdoe=$("#auto");
wordNodes.each(function(){
//获取单词内容 www.plcxue.com
var wordNode=$(this);
//新建div节点,取出单词内容,然后将单词加入到新建的节点中
$("<div>").html(wordNode.text()).appendTo(autoNdoe);
});
//让弹出框显示传回的数据
if(wordNodes.length>0){
$("#auto").show();
}
},"xml");
});
//给按钮添加事件,表示文本框中的数据被提交
$("input[type='button']").click(function(){
alert("文本框中的["+$("#word").val()+"]被提交了")
});
})
3、keyWord.jsp页面
复制代码 代码示例:
<%@ page language="java" contentType="text/xml;charset=utf-8"%>
<words>
<word>absolute</word>
<word>anyone</word>
<word>apple</word>
<word>abandon</word>
<word>a
break</word>
</words>
4、autoComplete.html代码
复制代码 代码示例:
<!doctype html public "-//w3c//dtd html 4.01 transitional//en">
<html>
<head>
<title>jquery仿google自动补全 - www.jb200.com</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/
javascript" src="js/jquery-1.4.2.js"></script>
<script type="text/javascript" src="js/autoComplete.js"></script>
</head>
<body>
<input type="text" id="word" />
<input type="button" value="提交" /><br>
<div id="auto"></div>
</body>
</html>