`

(转)自动补全

阅读更多
Servlet代码 复制代码
  1. /**   
  2.  * Servlet   
  3.  */   
  4. package com.wll.autoComplete;   
  5.   
  6. import java.io.IOException;   
  7.   
  8. import javax.servlet.ServletException;   
  9. import javax.servlet.http.HttpServlet;   
  10. import javax.servlet.http.HttpServletRequest;   
  11. import javax.servlet.http.HttpServletResponse;   
  12.   
  13. /**   
  14.  * 自动补全功能   
  15.  * 接收用户端请求   
  16.  * @author wll   
  17.  *   
  18.  */   
  19. public class AutoComplete extends HttpServlet {   
  20.     protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {   
  21.         //表示页面传过来的字符串,用于和服务器端的单词进行完整匹配   
  22.         String word = request.getParameter("word");   
  23.         //将字符串保存在request对象中   
  24.         request.setAttribute(Contants.PARAM, word);   
  25.         //将请求转发给视图层(注意AJAX中,这个所谓的视图层不返回页面,只返回数据,所以也可以称作是一个数据层)   
  26.         request.getRequestDispatcher("wordxml.jsp").forward(request, response);   
  27.     }   
  28.     protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {   
  29.         doGet(request,response);   
  30.     }   
  31. }  
/**
 * Servlet
 */
package com.wll.autoComplete;

import java.io.IOException;

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

/**
 * 自动补全功能
 * 接收用户端请求
 * @author wll
 *
 */
public class AutoComplete extends HttpServlet {
	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		//表示页面传过来的字符串,用于和服务器端的单词进行完整匹配
		String word = request.getParameter("word");
		//将字符串保存在request对象中
		request.setAttribute(Contants.PARAM, word);
		//将请求转发给视图层(注意AJAX中,这个所谓的视图层不返回页面,只返回数据,所以也可以称作是一个数据层)
		request.getRequestDispatcher("wordxml.jsp").forward(request, response);
	}
	protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}
}

 

常量类代码 复制代码
  1. /**   
  2.  *    
  3.  */   
  4. package com.wll.autoComplete;   
  5.   
  6. /**   
  7.  * 常类   
  8.  *    
  9.  * @author wll   
  10.  *    
  11.  */   
  12. public class Contants {   
  13.     public static final String PARAM = "param";   
  14.   
  15.     private Contants() {   
  16.   
  17.     }   
  18. }  
/**
 * 
 */
package com.wll.autoComplete;

/**
 * 常类
 * 
 * @author wll
 * 
 */
public class Contants {
	public static final String PARAM = "param";

	private Contants() {

	}
}

 

Jsp代码 复制代码
  1. <%@ page language="java" import="java.util.*"  
  2.  pageEncoding="utf-8"%>   
  3.   
  4. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">   
  5. <html>   
  6.   <head>   
  7.     <title>JQuery自动补全</title>   
  8.  <script type="text/javascript" src="js/jquery.js"></script>   
  9.     <script type="text/javascript" src="js/jqueryAuto.js"></script>   
  10.   </head>   
  11.      
  12.   <body>   
  13.     JQuery实例-自动补全:<input type="text" id="word" name="word" />   
  14.     <input type="button" id="buttonSubmit"  
  15.      name="buttonSubmit" value="提交" /><br />   
  16.     <div id="auto"></div>   
  17.   </body>   
  18. </html>  
<%@ page language="java" import="java.util.*"
 pageEncoding="utf-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>JQuery自动补全</title>
 <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript" src="js/jqueryAuto.js"></script>
  </head>
  
  <body>
    JQuery实例-自动补全:<input type="text" id="word" name="word" />
    <input type="button" id="buttonSubmit"
     name="buttonSubmit" value="提交" /><br />
  	<div id="auto"></div>
  </body>
</html>

 

输出结果的xml代码 复制代码
  1. <!-- ajax自动补全实例 -->   
  2. <!-- 与传统应用的视图层不同,这个jsp返回的是xml数据,因此contentType值是text/xml -->   
  3. <%@ page language="java" contentType="text/xml;charset=utf-8" %>   
  4. <%@page import="com.wll.autoComplete.Contants,java.util.*"%>   
  5. <!-- 返回xml数据的'视图层暂时不做任何逻辑判断,先所有单词都返回,   
  6. 待前后台应用可以完整的协作之后 ,再限制返回的内容' -->   
  7. <%   
  8.     //页面传送的字符串   
  9.     String word = (String)request.getAttribute(Contants.PARAM);   
  10.     List list = new ArrayList();   
  11.     list.add("absolute");   
  12.     list.add("anyone");   
  13.     list.add("apple");   
  14.     list.add("abandon");   
  15.     list.add("breach");   
  16.     list.add("break");   
  17.     list.add("bad");   
  18.     list.add("char");   
  19.     list.add("create");   
  20.     list.add("delete");   
  21.     list.add("java");   
  22.     list.add("attribute");   
  23. %>   
  24. <words>   
  25.     <%   
  26.     for(int i = 0;i < list.size();i ++) {   
  27.     if(list.get(i).toString().startsWith(word)) {%>   
  28.         <word><%=list.get(i)%></word>   
  29.     <%}}%>   
  30. </words>  
<!-- ajax自动补全实例 -->
<!-- 与传统应用的视图层不同,这个jsp返回的是xml数据,因此contentType值是text/xml -->
<%@ page language="java" contentType="text/xml;charset=utf-8" %>
<%@page import="com.wll.autoComplete.Contants,java.util.*"%>
<!-- 返回xml数据的'视图层暂时不做任何逻辑判断,先所有单词都返回,
待前后台应用可以完整的协作之后 ,再限制返回的内容' -->
<%
	//页面传送的字符串
	String word = (String)request.getAttribute(Contants.PARAM);
	List list = new ArrayList();
	list.add("absolute");
	list.add("anyone");
	list.add("apple");
	list.add("abandon");
	list.add("breach");
	list.add("break");
	list.add("bad");
	list.add("char");
	list.add("create");
	list.add("delete");
	list.add("java");
	list.add("attribute");
%>
<words>
	<%
	for(int i = 0;i < list.size();i ++) {
	if(list.get(i).toString().startsWith(word)) {%>
		<word><%=list.get(i)%></word>
	<%}}%>
</words>

 

Web.xml代码 复制代码
  1. <?xml version="1.0" encoding="UTF-8"?>   
  2. <web-app version="2.4"    
  3.     xmlns="http://java.sun.com/xml/ns/j2ee"    
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee    
  6.     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">   
  7.        
  8.   <servlet>   
  9.     <servlet-name>AutoComplete</servlet-name>   
  10.     <servlet-class>com.wll.autoComplete.AutoComplete</servlet-class>   
  11.   </servlet>   
  12.   <servlet-mapping>   
  13.     <servlet-name>AutoComplete</servlet-name>   
  14.     <url-pattern>/autoComplete</url-pattern>   
  15.   </servlet-mapping>   
  16.      
  17.   <welcome-file-list>   
  18.     <welcome-file>index.jsp</welcome-file>   
  19.   </welcome-file-list>   
  20. </web-app>  
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	
  <servlet>
  	<servlet-name>AutoComplete</servlet-name>
  	<servlet-class>com.wll.autoComplete.AutoComplete</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>AutoComplete</servlet-name>
  	<url-pattern>/autoComplete</url-pattern>
  </servlet-mapping>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

Js 代码代码 复制代码
  1. //表示当前高亮的节点   
  2. var highlightindex = -1;   
  3. var timeoutId;   
  4. $(document).ready(function(){   
  5.     var wordInput = $('#word');   
  6.     var wordInputOffset = wordInput.offset();   
  7.     //自动补全框最开始应该隐藏起来   
  8.     $('#auto').hide().css('border','1px black solid');   
  9.     //设置div的位置   
  10.     $('#auto').css('position','absolute');   
  11.     $('#auto').css('top',wordInputOffset.top + wordInput.height() + 5 + 'px');   
  12.     $('#auto').css('left',wordInputOffset.left + 'px');   
  13.     $('#auto').width(wordInput.width() + 6);   
  14.        
  15.     //给文本框添加键盘按下并弹起事件   
  16.     wordInput.keyup(function(event) {   
  17.         //处理文本框的键盘事件   
  18.         var myEvent = event || window.event;   
  19.         var keyCode = myEvent.keyCode;   
  20.         //如果输入的是字母,应该将文本框中最新的信息发送给服务器端   
  21.         //如果输入的是退格键或删除键,也应该像文本框中的最新信息发送给服务器端   
  22.         if(keyCode >= 65 && keyCode <=90 || keyCode == 8 ||keyCode == 46) {   
  23.             //1.首先获取文本框中的内容   
  24.             var wordText = $('#word').val();   
  25.             // 取得auto结点   
  26.             var autoNode = $('#auto');   
  27.             if(wordText != '') {   
  28.                 //对上次未完成的延时操作进行取消   
  29.                 clearTimeout(timeoutId);   
  30.                 //对于服务器端进行交互延迟500ms,避免快速打字造成的频繁请求   
  31.                 timeoutId = setTimeout(function(){   
  32.                     //2.将文本框中的内容发送给服务器   
  33.                     $.post("autoComplete",{   
  34.                     word:wordText   
  35.                     },function(data){   
  36.                         //将dom对象data转换成JQuery的对象   
  37.                         var jqueryObj = $(data);   
  38.                         //找到所有的word节点   
  39.                         var wordNodes = jqueryObj.find('word');   
  40.                            
  41.                         //需要清空原来的内容   
  42.                         autoNode.html('');   
  43.                         //遍历所有的word节点,取出单词内容,然后将单词内容添加到弹出框中   
  44.                         wordNodes.each(function(i){   
  45.                             //获取单词内容   
  46.                             var wordNode = $(this);   
  47.                             //新建div节点   
  48.                             //将新建的节点加入到弹出框的节点中    
  49.                             var newDivNode = $('<div>').attr('id',i);   
  50.                             newDivNode.html(wordNode.text()).appendTo(autoNode);   
  51.                             //增加鼠标进入事件,高亮节点   
  52.                             newDivNode.mouseover(function(){   
  53.                                 //将原来高亮的节点取消高亮   
  54.                                 if(highlightindex != -1) {   
  55.                                     $('#auto').children('div').eq(highlightindex)   
  56.                                     .css('background-color','white');   
  57.                                 }   
  58.                                 //记录新的高亮索引   
  59.                                 highlightindex = $(this).attr('id');   
  60.                                 //鼠标进入的节点高亮   
  61.                                 $(this).css('background-color','red');   
  62.                             });   
  63.                             //增加鼠标移出事件,取消高亮节点   
  64.                             newDivNode.mouseout(function(){   
  65.                                 $(this).css('background-color','white');   
  66.                             });   
  67.                             //增加鼠标点击事件,可以进行补全   
  68.                             newDivNode.click(function(){   
  69.                                 //取出高亮节点的文本内容   
  70.                                 var comText = $(this).text();   
  71.                                 $('#auto').hide();   
  72.                                 highlightindex = -1;   
  73.                                 //将文本框中的内容变成高亮节点的内容   
  74.                                 $('#word').val(comText);   
  75.                             });   
  76.                         });   
  77.                         //如果服务器端有数据返回,则显示弹出框   
  78.                         if(wordNodes.length > 0) {   
  79.                             autoNode.show();   
  80.                         } else {   
  81.                         //如果服务器端没有数据返回   
  82.                             autoNode.hide();   
  83.                         }   
  84.                     },   
  85.                     'xml');   
  86.                 },500);   
  87.             } else {   
  88.                 autoNode.hide();   
  89.                 //弹出框隐藏的同时,高亮节点索引值也置成-1  
  90.                 highlightindex = -1;   
  91.             }   
  92.         } else if(keyCode == 38 || keyCode == 40) {   
  93.             //如果输入的是向上38向下40按键   
  94.             if (keyCode == 38) {   
  95.                 //向上   
  96.                 var autoNodes = $('#auto').children('div');   
  97.                 if(highlightindex != -1) {   
  98.                     //如果存在高亮节点,则将背景色改为白色   
  99.                     autoNodes.eq(highlightindex).css('background-color','white');   
  100.                     highlightindex = highlightindex - 1;   
  101.                 } else {   
  102.                     highlightindex = autoNodes.length - 1;   
  103.                 }   
  104.                    
  105.                 if(highlightindex == -1) {   
  106.                     //如果修改索引值以后index变成-1,则将索引值指向最后一个元素   
  107.                     highlightindex = autoNodes.lenght - 1;   
  108.                 }   
  109.                 //让现在的高亮的内容变成红色   
  110.                 autoNodes.eq(highlightindex).css('background-color','red');   
  111.             }   
  112.             if (keyCode == 40) {   
  113.                 //向下   
  114.                 var autoNodes = $('#auto').children('div');   
  115.                 if(highlightindex != -1) {   
  116.                     //如果存在高亮节点,则将背景色改为白色   
  117.                     autoNodes.eq(highlightindex).css('background-color','white');   
  118.                 }   
  119.                 highlightindex = highlightindex + 1;   
  120.                 if(highlightindex == autoNodes.length) {   
  121.                     //如果修改索引值以后index变成-1,则将索引值指向最后一个元素   
  122.                     highlightindex = 0;   
  123.                 }   
  124.                 //让现在的高亮的内容变成红色   
  125.                 autoNodes.eq(highlightindex).css('background-color','red');   
  126.             }   
  127.                
  128.         } else if(keyCode == 13) {   
  129.             //如果输入的是回车   
  130.                
  131.             //下拉框有高亮内容   
  132.             if(highlightindex != -1) {   
  133.                 //取出高亮节点的文本内容   
  134.                 var comText = $('#auto').hide().children('div')   
  135.                 .eq(highlightindex).text();   
  136.                 highlightindex = -1;   
  137.                 //将文本框中的内容变成高亮节点的内容   
  138.                 $('#word').val(comText);   
  139.             } else {   
  140.                 //下拉框无高亮内容   
  141.                 alert('没有选择高亮内容');   
  142.                 $('#auto').hide();   
  143.                 //让文本框失去焦点   
  144.                 $('#word').get(0).blur();   
  145.             }   
  146.         }   
  147.     });   
  148.        
  149.     //给按钮添加事件,表示文本框中的数据被提交$("input[type]='button']")   
  150.     $('#buttonSubmit').click(function(){   
  151.         alert('文本框中的【' + $('#word').val() + '】被提交了');   
  152.     }) ;   
  153.        
  154. });  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics