繁体   English   中英

如何使用jQuery的自动完成功能?

[英]how to use jquery autocomplete?

我正在使用JSP创建一个Web项目,并且正在尝试使用jquery自动完成功能从我的数据库中为用户实现简单的搜索,但是我无法理解它的工作原理。 我对jquery和ajax几乎一无所知,只是想让您知道。 我完成了以下代码,并被卡住。

<%@page contentType="text/html" pageEncoding="UTF-8" import="ewa.dbConnect,ewa.sendEmail,ewa.pwGen,ewa.hashPw,java.sql.*" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <link rel="stylesheet" type="text/css" href="css/jquery.autocomplete.css" />
        <script src="js/jquery.autocomplete.js"></script>
        <script type="text/javascript"
            src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <input type="text" id="search" name="search"/>
        <script>
        $("#search").autocomplete("getdata.jsp");
    </script>
    </body>
</html>

getdata.jsp

<%@page contentType="text/html" pageEncoding="UTF-8" import="ewa.dbConnect,java.sql.*" %>
<%! dbConnect db = new dbConnect(); %>
<%
String query = request.getParameter("q");
db.connect();
Statement stmt = db.getConnection().createStatement();
ResultSet rs = stmt.executeQuery("SELECT username FROM created_accounts WHERE username LIKE "+query);
while(rs.next())
{
    out.println(rs.getString("username"));
}
db.disconnect
%>

如果我没看错,我是从网站上读取的,参数q是默认值,就在其中,但是如何显示数据? 我如何将值从getdata.jsp传递到自动完成功能?

您在包含jQuery之前调用了自动完成脚本标记。 因此,没有jQuery可以锁定(因为尚未定义jQuery对象),因此jQuery自动完成插件不会加载任何内容。

你有

 <script src="js/jquery.autocomplete.js"></script>
 <script type="text/javascript"
     src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

它应该是

    <script type="text/javascript"
        src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
    <script src="js/jquery.autocomplete.js"></script>

颠倒顺序,您提到的Firebug错误应该消失; 我不确定它是否能解决所有问题,但是在解决之前没有任何作用。

我没有看到包含jQuery UI(该UI提供了自动完成功能)

http://jqueryui.com/demos/autocomplete/

因此,您需要包括jquery.ui.autocomplete.js(或者您是否正在使用插件自动完成功能?如果是,请移至jquery UI版本)

也可能是来自getdata.jsp的数据格式错误,无法用于自动完成。

您如何尝试在浏览器(例如chrome)或firefox(带有firebug)中调试javascript

我通常给(用于jQuery UI自动完成功能)一个JSON格式的答案,而我看到您的答案循环给出了一个CR分隔列表。

在getdata.jsp中而不是产生:

jim<cr>
jack>cr>
jhon<cr>

尝试返回:

[{label: 'jim', value: 'jim'}, {label:
 'jack', value: 'jack'}, {label:
 'jhon', value: 'jhon'}]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM