• 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){
                          if(data!=null||!"".equals(data)){
                              var str = "";
                              $.each(data,function(n,obj){
                                 $("#autocomplete").show();
                                  str = "<li>"+obj.name+"<li>";
                                  $("#autocomplete").append(str);
                                   $("li").click(function(){
                                    //当点击哪个列表时就把它的值load到输入框中
                                     $("#search-text").val($(this).text());
                                     $("#autocomplete").empty();
                                     });
    //鼠标移到当前元素和移出当前元素的背景色 $(
    "li").hover(function(){ $(this).addClass("clor"); },function(){ $(this).removeClass("clor"); }); }); } }, error:function(textStatus){ //alert(textStatus); } }); } function lost(){ //$("#autocomplete").empty(); } </script> <style type="text/css"> li{ list-style:none; padding-top:2px; width:150px; } ul{ margin-top:5px; margin-left:-40px; } a{ text-decoration:none; color:#5C5C5C; } .clor{ background-color:#ADADAD; } </style> </head> <body> <form action="EntyToJson" method="post"> <div id="selelist"> <input type="text" id="search-text" name="searchValue" value="" maxlength="200" onkeyup="autocomple()" > <input type="submit" value="搜索"/> </div> </form> </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;
        }

    效果截图:

  • 相关阅读:
    asp.net GDI+绘制矩形渐变
    asp.net GDI+把图片绘制成自定义的椭圆形状
    asp.net TreeView控件绑定数据库显示信息
    asp.net GridView控件中诗选全选和全不选功能
    PHP 笔记——会话控制
    PHP 笔记——String 字符串
    PHP 笔记——Web页面交互
    PHP 笔记——PDO操作数据库
    PHP 笔记——操作MySQL数据库
    PHP 笔记——Array 数组
  • 原文地址:https://www.cnblogs.com/kailing-con/p/4276111.html
Copyright © 2020-2023  润新知