js搜索提示仿百度搜索

仿百度搜索,用的基本的js事件和ajax请求,服务器后端返回xml类型,代码比较齐全,基本上可以直接使用。

<style>
#auto_div{ 
    position:absolute; 
    border-width:1px; 
    border:1px #808080 solid; 
} 
</style>
<input type="text" name="userName" id="auto_txt" value=""/>
<div style="border-width:1px; background-color: white;" id="auto_div"></div>
//高亮的索引 
	var highLightIndex = -1; 
	//超时的标识(对用户连续快速按下键盘的事件做延时处理,只对用户在500ms内最后一次请求,让其生效) 
	var timeoutId; 
$(document).ready(function(){ 
	   init(); 
	   $('#auto_txt').bind('keyup',processKeyup); 
	}); 
	
	/*** 
	 * 初始化弹出框列表的位置,大小 
	 */ 
	function init(){ 
	   $('#auto_div').hide(); 
	   var pos = $('#auto_txt').position(); 
	   var topPosition = pos.top+$('#auto_txt').height()+7; 
	   var leftPosition = pos.left; 
	   $('#auto_div').offset({top:topPosition,left:leftPosition}); 
	   $('#auto_div').width(131); 
	} 
/** 
     * 处理点击鼠标后使div消失
     * @param event 
     */ 
	document.onclick = function(event){     
        var e = event || window.event;  
        var elem = e.srcElement||e.target;  
        while(elem){   
            if(elem.id == "auto_div"){  
                    return;  
            }  
            elem = elem.parentNode;       
        }  
        //隐藏div的方法  
        $('#auto_div').hide(); 
    }  
	
	/** 
     * 处理键盘按下后弹起的事件 
     * @param event 
     */ 
    function processKeyup(event){ 
	    var myEvent = event || windows.event; 
	    var keyCode = myEvent.keyCode; 
	    //输入是字母,或者退格键则需要重新请求 
	    if((keyCode >= 65 && keyCode <= 90) 
	    		|| keyCode == 32 
	    		|| (keyCode >= 48 && keyCode <= 57)){ 
	         //以下两行代码是为了防止用户快速输入导致频繁请求服务器 
	         //这样便可以在用户300ms内快速输入的情况下,只请求服务器一次 
	         //大大提高服务器性能 
	         highLightIndex = -1; 
	         clearTimeout(timeoutId); 
	         timeoutId = setTimeout(processAjaxRequest,300); 
	    //处理上下键(up,down) 
	    }else if(keyCode == 38 || keyCode == 40){ 
	        processKeyUpAndDown(keyCode); 
	    //按下了回车键 
	    }else if(keyCode == 13){ 
	        processEnter(); 
	    } 
     }
	
/** 
     * 处理Ajax请求 
     * @param data 
     */ 
    function processAjaxRequest(){
        $.ajax({ 
            type:"post",       //http请求方法,默认:"post" 
            url:"${contextPath}/common/ajaxCheckName/"+$('#auto_txt').val(),   //发送请求的地址 
            dataType:"xml",   //预期服务器返回的数据类型 
            success:processAjaxResponse 
         }); 
    }

    /** 
     * 处理Ajax回复 
     * @param data Ajax请求得到的返回结果为dom文档对象 
     */ 
    function processAjaxResponse(data){
        $('#auto_div').html('').show(); 
        $('#auto_div').css('z-index','999'); 
        $('#auto_div').css('position','absoulte'); 
        var xml = $(data);
        var words = xml.find('word'); 
        if(words.length == 0){
        	$('#auto_div').html('无搜索数据');
        }
        for(var i = 0 ; i < words.length ; i ++){ 
           var word_div = $('<div></div>'); 
           word_div.html(words.eq(i).text()); 
           word_div.hover(fnOver,fnOut); 
           word_div.click(getAutoText); 
           $('#auto_div').append(word_div); 
        } 
    }
    
    /** 
     * 处理鼠标滑过 
     */ 
    function fnOver(){ 
         changeToWhite(); 
         $(this).css('background-color','cyan'); 
         highLightIndex = $(this).index(); 
         //下面一行注释掉了,百度搜索也没这功能,就是鼠标移动时,跟着改变搜索框的内容 
         //$('#auto_txt').val($('#auto_div').children().eq(highLightIndex).html()); 
    } 
    
    /** 
     * 处理鼠标移除 
     */ 
    function fnOut(){ 
        $(this).css('background-color','white'); 
    } 

    /** 
     * 得到自动填充文本 
     */ 
    function getAutoText(){ 
       //有高亮显示的则选中当前选中当前高亮的文本 
       if(highLightIndex != -1){ 
           $('#auto_txt').val($(this).html().trim()); 
           $('#auto_div').html('').hide(); 
       } 
    } 
    
    /** 
     * 处理按下Enter键 
     * @param keyCode 
     */ 
    function processEnter(){ 
        if(highLightIndex != -1){ 
           $('auto_txt').val($('#auto_div').children().eq(highLightIndex).html().trim()); 
           $('#auto_div').html('').hide(); 
        } 
    } 

    /** 
     * 处理按上下键的情况 
     */ 
    function processKeyUpAndDown(keyCode){ 
        var words = $('#auto_div').children(); 
        var num = words.length; 
        if(num <= 0) return; 
        changeToWhite(); 
        highLightIndex = ((keyCode != 38 ? num + 1:num - 1)+highLightIndex) % num; 
        words.eq(highLightIndex).css('background-color','cyan'); 
        $('#auto_txt').val(words.eq(highLightIndex).html().trim()); 
    } 

    /** 
     * 如果有高亮的则把高亮变白 
     */ 
    function changeToWhite(){ 
        if(highLightIndex != -1){ 
            $('#auto_div').children().eq(highLightIndex).css('background-color','white'); 
        } 
    }

后台处理ajax请求的代码,包括List转换为XML

public void ajaxCheckName(@PathVariable String userName, HttpServletResponse response) throws IOException, Exception {
		List<UserInfo> userInfoList = hrUserInfoService.getUserListByName(userName);
		List<String> nameList = new ArrayList<String>();
		for(UserInfo userInfo : userInfoList){
			nameList.add(userInfo.getUserName());
		}
		response.setContentType("text/xml");
        response.setHeader("Cache-Control", "no-cache");
        response.getWriter().write(new StringUtil().list2Xml(nameList));
	}

/**
	 * 
	 * @method list2Xml
	 * @description List转换为XML
	 * 
	 * list to xml xml <words><word><key label="key1">value1</key><key 
     * label="key2">value2</key>......</word><word><key 
     * label="key1">value1</key><key 
     * label="key2">value2</key>......</word></words> 
     * 
	 * @param list
	 * @return
	 * @throws Exception 
	 * @author chengpp
	 * @date 2014-11-20 下午4:57:35 
	 *
	 */
	public String list2Xml(List<String> list) throws Exception {  
        Document document = DocumentHelper.createDocument();  
        Element wordsElement = document.addElement("words");  
        int i = 0;  
        for (Object o : list) {  
            Element wordElement = wordsElement.addElement("word");  
            if (o instanceof Map) {  
                for (Object obj : ((Map<?, ?>) o).keySet()) {  
                    Element keyElement = wordElement.addElement("key");  
                    keyElement.addAttribute("label", String.valueOf(obj));  
                    keyElement.setText(String.valueOf(((Map<?, ?>) o).get(obj)));  
                }  
            } else {  
                Element keyElement = wordElement.addElement("key");  
                keyElement.addAttribute("label", String.valueOf(i));  
                keyElement.setText(String.valueOf(o));  
            }  
            i++;  
        }  
        return doc2String(document);  
    }  
    
    /** 
     *  
     * @param document 
     * @return 
     */  
    public String doc2String(Document document) {  
        String s = "";  
        try {  
            // 使用输出流来进行转化  
            ByteArrayOutputStream out = new ByteArrayOutputStream();  
            // 使用UTF-8编码  
            OutputFormat format = new OutputFormat("   ", true, "UTF-8");  
            XMLWriter writer = new XMLWriter(out, format);  
            writer.write(document);  
            s = out.toString("UTF-8");  
        } catch (Exception ex) {  
            ex.printStackTrace();  
        }  
        return s;  
    }

相关推荐