AJAX自动填充不在测试框中显示建议值

时间:2013-11-06 01:09:18

标签: javascript jsp jquery

自动填充不在文本框中显示建议值。但后端查询执行并获得结果,它没有显示在文本框中。请告诉我如何在文本字段中显示建议框。

<!DOCTYPE>
<html>
<head>
<title>Auto Complete in JSP Java</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<script>
$(function() {
$("#names").autocomplete({
    source: function(request, response) {
    $.ajax({
    url: "searchName.jsp",
    type: "POST",
    dataType: "text",
    data: { name: request.term},
    success: function( data ) {
    //alert(data);

        response( $.map( data, function( item ) {
        return {
            label: item.name,
            value: item.value,
        }
        }));
    },
    error: function (error) {
       alert('error: ' + error);
    }
    });
    },
    minLength: 3
    });
});
</script>
</head>

<body>
<input type="text" name="name" id="names" /> 
</body>
</html>

searchnames.jsp

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

   <%
  String query = (String)request.getParameter("name");
   try{
     String s[]=null;
      Class.forName("oracle.jdbc.driver.OracleDriver");
     Connection con DriverManager.getConnection("XXXX");
     Statement st=con.createStatement();
     ResultSet rs = st.executeQuery("select name from Table1 where name like '"+query+"%'");
     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++;
       }

       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++;
            }
       }

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

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


%>

请告诉我......

1 个答案:

答案 0 :(得分:0)

似乎你的.jsp没有输出json格式。你需要改变这一行

out.print(str[j]+"\n");

out.print("\"name\" : " + "\"" + str[j]+"\"\n");

然后在你的javascript代码中

response( $.map( data, function( item ) {
    return {
        label: item.name,
        value: item.name,
    }
    }));

请参阅more about JSON format here

出于提供信息的目的我将字符串与operator +连接,尝试使用StringBuilder以获得更好的性能。