//下面是我的表单页面,带有一个国家/地区文本框,我想显示所有字母以字母开头和自动完成的国家/地区,并使用数据库中的值用jsp,java,jquery自动显示我数据库中的国家/地区

<html>
<head>
<link href = "https://code.jquery.com/ui/1.10.4/themes/uilightness/jquery-    ui.css"rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script>
$(document).ready(function() {
$('#country').focusin(function() {
$("#country").autocomplete("List.jsp");
});
});
</script>
</head>
<body>
    <br><br><center>
        <font face="verdana" size="2">
        <font size="4">Java(jsp)/jQuery Autocompleter Example</font>
        <br><br><br><br>

        Select Country   :
        <input type="text" id="country" name="country"/>

        </font>
    </body>
</html>


//下面是与数据库连接的List.jsp页面

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<%@page import="java.util.*"%>

<%
    try {
        String s[] = null;

        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("Driver found");
        String url = "jdbc:mysql://localhost:protNum/dbName";
        String user = "";
        String pass = "";
        System.out.println("Connected....");
        Connection con = (Connection) DriverManager.getConnection(url, user, pass);
        Statement st = con.createStatement();
        ResultSet rs = st.executeQuery("select * from tbctry");

        List li = new ArrayList();

        while (rs.next()) {
            li.add(rs.getString(1));
        }

        String[] str = new String[li.size()];
        Iterator it = li.iterator();

        int i = 0;
        while (it.hasNext()) {
            String p = (String) it.next();
            str[i] = p;
            i++;
        }

        //jQuery related start
        String query = (String) request.getParameter("q");

        int cnt = 1;
        for (int j = 0; j < str.length; j++) {
            if (str[j].toUpperCase().startsWith(query.toUpperCase())) {
                out.print(str[j] + "\n");
                if (cnt >= 5)// 5=How many results have to show while we are typing(auto suggestions)
                {
                    break;
                }
                cnt++;
            }
        }
 //jQuery related end

        rs.close();
        st.close();
        con.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
%>

最佳答案

//以下是使用json和jquery的自动完成的实现
// Jsp表单页面,用于在用户输入“自动完成”功能的第一个字母时输入国家名称作为文本框

<!DOCTYPE html>
<html>
    <head>
        <meta charset="ISO-8859-1">
        <title>Autocomplete in java web application using Jquery and JSON</title>
        <script src="//code.jquery.com/jquery-1.10.2.js"></script>
        <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
        <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
        <script>
            $(document).ready(function() {
                $(function() {
                    $("#search").autocomplete({
                        source: function(request, response) {
                            $.ajax({
                                url: "CountryListCheck",
                                type: "GET",
                                data: {
                                    term: request.term
                                },
                                dataType: "json",
                                success: function(data) {
                                    response(data);
                                }
                            });
                        }
                    });
                });
            });
        </script>


    </head>
    <body>
        <div class="header">
            <h3>Autocomplete in java web application using Jquery and JSON</h3>
        </div>
        <br />
        <br />
        <div class="search-container">
            <div class="ui-widget">
                country:
                <input type="text" id="search" name="search" class="search" />
            </div>
        </div>
    </body>
</html>


//以下是放置在与URL CountryListCheck对应的控制器上的代码

 "/CountryListCheck":
    String term = request.getParameter("term");
    System.out.println("Data from ajax call " + term);
                    ArrayList<String> list = new Op_contact(dcon).getAllCountriesCheck(term);
                    System.out.println(list);
                     Json = new Gson().toJson(list);
                   response.getWriter().write(Json );


//下面是操作类代码或数据库查询部分

public ArrayList<String> getAllCountriesCheck(String l) {
        ArrayList<String> list = new ArrayList<String>();
        PreparedStatement ps = null;
        String data;
        try {
            String ch=l+"%";
            ps = (PreparedStatement) dcon.con.prepareStatement("SELECT nicename FROM tbctry  WHERE nicename  LIKE '"+ch+"'");
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                data = rs.getString("nicename");
                System.out.println(data);
                list.add(data);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return list;
    }

10-05 18:39
查看更多