首先浏览实现后的结果,输入一个a之后会出现包含a的下拉列表,当我们点击某一个的时候,搜索框中就会出现点击的值。实现所需要的主要是ajax+js。
前端search.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>Insert title here
后台searchServlet.Java
package search; import java.io.IOException; import java.util.ArrayList; import java.util.List; import net.sf.json.JSONArray; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class searchServlet */ @WebServlet("/searchServlet") public class searchServlet extends HttpServlet { private static final long serialVersionUID = 1L; static Listdatas=new ArrayList (); static {//假数据,模拟数据库读取 datas.add("ajax"); datas.add("bjax"); datas.add("ajaxfd"); datas.add("bfvd"); datas.add("dafdx"); datas.add("fdax"); datas.add("ahg"); datas.add("ddx"); } /** * @see HttpServlet#HttpServlet() */ public searchServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String keyword=request.getParameter("keyword"); //System.out.println(keyword); List listdata= getData(keyword); // 返回json,以流的形式写到前台 response.getWriter().write(JSONArray.fromObject(listdata).toString()); } //获取假数据中符合条件的值 public List getData(String keyword) { List list=new ArrayList (); for(String data:datas) { if(data.contains(keyword)){ list.add(data); } } return list; } }
xml配置
<?xml version="1.0" encoding="UTF-8"?>
searchServlet
search.searchServlet
searchServlet
/search/searchServlet
DropMeum
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
目录结构
总结
以上所述是小编给大家介绍的JS+Ajax实现百度智能搜索框,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!