使用jQuery模拟Google的自动提示效果

注意:

1、本功能使用SqlServler2000中的示例数据库Northwind,请打SP3或SP4补丁;
2、请下载jQuery组件,河西FTP中有下载;
3、本功能实现类似Google自动提示的效果,通过ajax引擎从服务器获取,返回XML数据;
4、本示例程序没考虑性能问题;
5、不支持Firefox浏览器,因为该浏览器没有propertychange事件。

步骤:

1、创建一个名为GoogleServlet的Servlet,负责从数据库中读取数据并生成XML格式的数据。

package com.aptech.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GoogleServlet extends HttpServlet {

    public void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/xml;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String key = request.getParameter("key");
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            Connection conn = DriverManager.getConnection("jdbc:sqlserver://127.0.0.1:1433;DatabaseName=northwind", "sa", "");
            PreparedStatement pstmt = conn.prepareStatement("select shipname, count(shipname) as c from [orders] where shipname like ? group by shipname");
            pstmt.setString(1, key + "%");
           
            ResultSet rs = pstmt.executeQuery();
           
            StringBuilder xml = new StringBuilder();
            xml.append("<results>");
            if(rs != null){
                while(rs.next()){
                    xml.append("<result key=""" + rs.getString(1) + """ count=""" + rs.getInt(2) + """></result>");
                }
            }
            xml.append("</results>");
            rs.close();
            pstmt.close();
            conn.close();
           
            out.print(xml.toString());
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
       
        out.flush();
        out.close();
    }
}

2、定义一个名为google.html的HTML文件,负责动态生成自动提示的效果。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>google.html</title>
   
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="jquery-1.2.6.pack.js"></script>

    <script type="text/javascript">
        var line = 0;
       
        function del(){
            if($("#newDiv")){
                $("#newDiv").remove();
                line = 0;
            }
        }
   
        $(document).ready(function(){
            //文本框失去焦点时层消失
            $(document.body).click(function(){
                del();
            });
           
            $(document).keydown(function(){
                // 38 上  40下 13 回车
                if($("#newDiv")){
                    if(event.keyCode == 40){
                        $("table tbody tr").eq(line)
                            .css("backgroundColor", "blue")
                            .css("color", "white");
                        $("table tbody tr").eq(line < 0 ? 0 : line - 1)
                            .css("backgroundColor", "white")
                            .css("color", "black");
                        line = (line == $("table tbody tr").length ? 0 : line + 1);
                    }else if(event.keyCode == 38){
                        line = (line == 0 ? $("table tbody tr").length : line - 1);
                        $("table tbody tr").eq(line)
                            .css("backgroundColor", "blue")
                            .css("color", "white");
                        $("table tbody tr").eq(line > $("table tbody tr").length ? 0 : line + 1)
                            .css("backgroundColor", "white")
                            .css("color", "black");
                    }else if(event.keyCode == 13){
                        $("#key").val($("table tbody tr").eq(line - 1).find("td").eq(0).html());
                        del();
                    }
                }   
            });
       
            $("#key").bind("propertychange", function(){
                del();
           
                var top = $("#key").offset().top;
                var left = $("#key").offset().left;
                var newDiv = $("<div/>").width($("#key").width() + 6)
                    .css("position", "absolute")
                    .css("backgroundColor", "white")
                    .css("left", left)
                    .css("top", top + $("#key").height() + 6)
                    .css("border", "1px solid blue")
                    .attr("id", "newDiv");
                   
                var table = $("<table width=‘100%‘/>")
                    .attr("cellpadding", "0")
                    .attr("cellspacing", "0");
                   
                $.post("GoogleServlet", {key: $("#key").val()}, function(xml){
                    $(xml).find("results result").each(function(){
                        var key = $(this).attr("key");
                        var count = $(this).attr("count");
                       
                        var tr = $("<tr/>").css("cursor", "pointer").mouseout(function(){
                            $(this).css("backgroundColor", "white").css("color", "black");
                        }).mouseover(function(){
                            $(this).css("backgroundColor", "blue").css("color", "white");
                        }).click(function(){
                            $("#key").val($(this).find("td").eq(0).html());
                           
                            del();
                        });
                        var td1 = $("<td/>").html(key).css("fontSize", "12px")
                            .css("margin", "5 5 5 5");
                        var td2 = $("<td/>").html("共有" + count + "个结果")
                            .attr("align", "right").css("fontSize", "12px")
                            .css("color", "green").css("margin", "5 5 5 5");
                       
                        tr.append(td1).append(td2);
                        table.append(tr);
                        newDiv.append(table);
                    });
                });
               
                $(document.body).append(newDiv);
               
                if($("#key").val() == ""){
                    $("#newDiv").remove();
                }               
            });
        });
    </script>
  </head>
 
  <body>
    <h1>Google搜索</h1>
    <div style="margin-top: 20px; margin-left: 30px">
        请输入搜索关键字:<input name="key" id="key" style="width: 300">
    <input type="button" value="Goolge一下">
    </div>
  </body>
</html>

3、最后的效果:

使用jQuery模拟Google的自动提示效果,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。