完成的功能 如:
第步一新建一个web工程:autoCompleteStart
二 向工程新添搜索页面 如:
JQueryAutoComplete.html
三 新建一个servlert com.test.autocom.sAutoComplete.java
package com.test.autocom;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class AutoComplete extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String world = request.getParameter("world");
request.setAttribute("world", world);
//在Ajax的请求当中它不返回一个页面,只返回它所请求的数据,所以也可以称作为数据层
request.getRequestDispatcher("worldxml.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
四 配置web.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
新建一个worldxml.jsp页面用于返回 定义查询数据的内容
<%@ page language="java" contentType="text/xml; charset=utf-8"%>
<%
String word = (String)request.getAttribute("world");
%>
<%if("absolute".startsWith(word)){%>
<%}%>
<%if("anyone".startsWith(word)){%>
<%}%>
<%if("anything".startsWith(word)){%>
<%}%>
<%if("apple".startsWith(word)){%>
<%}%>
<%if("abandom".startsWith(word)){%>
<%}%>
<%if("breach".startsWith(word)){%>
<%}%>
<%if("break".startsWith(word)){%>
<%}%>
在webRoot目录下新建一个Jslib目录并在这个目录拷入jquery.js使用jquery必须的文件
在这个目录下新建jqueryauto.js 这个js文件里面完成js的触发方法的操作内容如下:
//用于定位键盘上下时,保证返回的数据条有光亮的部分
var heightLightIndex = -1;
var timeoutid;
$(document).ready(function(){
var wordInput = $('#word');
var wordInputOffset = wordInput.offset();
$('#auto').hide().css("border","1px black solid").css("position","absolute")
.css("top",wordInputOffset.top+wordInput.height()+5+"px")
.css("left",wordInputOffset.left+"px").width(wordInput.width()+2+"px");
//给文本添加键盘按下并弹起的事件
wordInput.keyup(function(event){
var myEvent = event || window.event;
var keyCode =myEvent.keyCode;
//8,46是退格键和删除键
if(keyCode>=65&&keyCode<=90||keyCode==8||keyCode==46){
var worldText = $('#word').val();
if(worldText != ""){
//取消上次未完成都的延迟操作
clearTimeout(timeoutid);
timeoutid = setTimeout(function(){
$.post("AutoComplete",{world:worldText},function(data){
var jqueryObj = $(data);
var worldNodes = jqueryObj.find("world");
var autoNode = $('#auto');
autoNode.html("");
//each中的第一参数就是所遍历这个数组的下标
worldNodes.each(function(i){
var wordNode = $(this);
var newDivNode = $('