jQuery自动显示搜索下拉框
描述:当用选择查询时,根据输入的关键字动态从后台模糊查询,把结果异步显示在前端。
jsp代码;
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>自动显示搜索下拉表单</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <!-- 引入jquery --> <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.9.1.js"></script> <script language="javascript" type="text/javascript"> $(function(){ $("<ul id=‘autocomplete‘></ul>").hide().insertAfter("#search-text"); //不能在这里定义自定义的函数,否则无效!! }); function autocomple(){ $("#autocomplete").empty(); // alert("478"); $.ajax({ url:"EntyToJson", type:"post", data:"name="+$("#search-text").val(), dataType:"json", success:function(data,textStatus){ var str = ""; $.each(data,function(n,obj){ $("#autocomplete").show(); str = "<li>"+obj.name+"<li>"; $("#autocomplete").append(str); }); }, error:function(textStatus){ //alert(textStatus); } }); } function lost(){ $("#autocomplete").empty(); } </script> </head> <body> <div id="selelist"> <input type="text" id="search-text" name="searchValue" value="" maxlength="200" onkeyup="autocomple()" onblur="lost()"> </div> </body> </html>
服务端代码:
EntyToJson.java
package ajaxServlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.logging.SimpleFormatter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dao.UserDao; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import enty.User; /** * 功能描述:jQuery控制自动提示搜索下拉框 * @author Administrator * */ public class EntyToJson extends HttpServlet { /** * Constructor of the object. */ public EntyToJson() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/json"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); //接收值 String name = request.getParameter("name"); if(!"".equals(name)){ UserDao userDao = new UserDao();
//进行模糊查询,并返回对象集合列表 List users = userDao.getUsersForName(name); //集合要调用json对象数组JSONArray类 JSONArray jsonObject = JSONArray.fromObject(users); //单个对象要调用jsonobject类 //JSONObject jsonObject2 = JSONObject.fromObject(user1); out.println(jsonObject.toString()); } } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } public static void main(String args[]){ } }
数据访问层代码:
//模糊查询 public List<User> getUsersForName(String name){ try { Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); String hql = "from User where name like ‘%"+name+"%‘"; List list = session.createQuery(hql).list(); session.beginTransaction().commit(); session.close(); return list; } catch (Exception e) { e.printStackTrace(); } return null; }
效果截图:
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。