使用Ajax实现百度下拉框

百度下拉框

在使用百度搜索时,在输入框中输入部分文字后,下面会将与该文字相关的词组展示出来,该功能就可以使用ajax来实现。
注册输入框的onkeyup事件,该事件触发时,将输入框中填写的内容使用ajax发送到servlet中,在servlet中根据用户的输入去数据库中查询,之后将查询出的数据再发送给jsp中,最后将该数据展示在页面即可。

效果图(当然这里页面做的比较简单):输入一个火字即出现以下效果,并可以点击使文本框中内容变为点击的内容。

代码如下(注:其中引用的MyAjax.js在上一个博客):

首先是JSP(baidu.jsp):

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>百度下拉框</title>
</head>
<body>
   
  <!-- 用户输入框 -->
<div id="divsearch">
        <input type="text" name="name" id="name" />
        <input type="submit" value="搜索">

</div>
<!-- 下拉提示框 -->
<div id="tips" style="display: none; border: 1px solid red; background-color: white; width: 171px; top: 135px;"></div>
</body>
<script type="text/javascript" src="${pageContext.request.contextPath }/MyAjax.js"></script>
<script type="text/javascript">
	window.onload = function(){
		
		var searchElement = document.getElementById("name");
		
		//获取下拉提示框的div对象
		var div = document.getElementById("tips");
		
		//给输入框注册按键弹起事件
		searchElement.onkeyup = function(){
			//获取输入框的值
			var name = this.value;
			//如果输入框没有内容,将下拉提示框隐藏
			if(name == ""){
				div.style.display = "none";
				return;
			}
			
			//获取XMLHttpRequest对象
			var xhr = getXMLHttpRequest();
			
			//回调函数
			xhr.onreadystatechange = function(){
				if(xhr.readyState == 4){
					if(xhr.status == 200){
						var str = xhr.responseText;//获取服务器返回的数据
						if(str == ""){
							return;
						}
						
						//返回数据格式以","区分的字符串,例如:monkey,小猴子,1024
						//var result = str.split(",");//result:{"monkey","小猴子","1024"}
						//使用json格式进行数据传输
						var result = JSON.parse(str);
						var childDivs = "";
						//循环把数据放入到div中
						for(var i=0; i<result.length; i++){
							childDivs += "<div onclick='writeText(this)' onmouseover='changeBackgroundColor(this)' onmouseout='recoverBackgroundColor(this)'>" + result[i] + "</div>";
							//childDivs += "<div>"+result[i]+"</div>";
						}
						console.log(childDivs);
						//把多个childDivs放入列表div中
						div.innerHTML = childDivs;
						//将列表显示
						div.style.display = "block";
					}
				}
			}
			
			xhr.open("get","${pageContext.request.contextPath}/search?name="+ name+"&time="+new Date().getTime());
			xhr.send(null);
		}
	}
	
	//将文本填充到搜索框
	function writeText(div){
		//获取搜索框对象
		var searchElement = document.getElementById("name");
		//将选中的div的值添加到搜索框中
		searchElement.value = div.innerHTML;
		//将下拉提示框隐藏
		div.parentNode.style.display = "none";
	}
	
	//鼠标悬浮时,改变背景色
	function changeBackgroundColor(div){
		div.style.backgroundColor = "orange";
	}
	//鼠标离开时,回复背景色
	function recoverBackgroundColor(div){
		div.style.backgroundColor = "";
	}
</script>
</html>

Servlet部分(SearchServlet.java):

package com.rong.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 com.alibaba.fastjson.JSONArray;

/**
 * Servlet implementation class SerchServlet
 */
@WebServlet("/search")
public class SerchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//解决乱码问题
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
        //获取Ajax传过来的数据
		String name = request.getParameter("name");
		
		//根据用户的输入查询数据库,这里省略数据库的操作,手动创建一个List
		List<String> result = new ArrayList<>();
        result.add("火影忍者");
        result.add("火影博人传");
        result.add("火影还在更吗");
        result.add("火影鸣人");
        result.add("火花");

        //把集合中的数据转换为字符串返回到网页
        String str = "";
        //如果用户输入的内容是以m开头的话,则将数据返回
        if(name.startsWith("火")){
//            for (int i = 0; i < result.size(); i++) {
//                if(i>0){
//                    str+=",";
//                }
//                str+=result.get(i);
//            }
        
        //使用Json格式进行数据传输
        str = JSONArray.toJSONString(result);
        }

        System.out.println(str);
        //把数据响应到客户端
        response.getWriter().write(str);
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
发布了60 篇原创文章 · 获赞 10 · 访问量 9208

猜你喜欢

转载自blog.csdn.net/chaseqrr/article/details/103738682