[英]AJAX Autocomplete not showing suggestions values in test box
Autocomplete not showing the suggestion values in text box. 自动完成功能不会在文本框中显示建议值。 but back end query executed and got the results, it's not showing up in the text box.
但是执行了后端查询并获得了结果,它没有显示在文本框中。 Please advise me how to showup the suggestionsbox in the text field.
请告诉我如何在文本字段中显示建议框。
<!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 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();
}
%>
Please advise me... 请建议我...
it seems your .jsp is not outputting json format. 看来您的.jsp没有输出json格式。 you would need to change this line
您需要更改此行
out.print(str[j]+"\n");
to 至
out.print("\"name\" : " + "\"" + str[j]+"\"\n");
and then in your javascript code 然后在您的JavaScript代码中
response( $.map( data, function( item ) {
return {
label: item.name,
value: item.name,
}
}));
see more about JSON format here 在这里查看有关JSON格式的更多信息
for informative purposes I'm concatenating Strings with operator +, try to use StringBuilder for better performance. 为了提供更多信息,我将字符串与运算符+连接在一起,请尝试使用StringBuilder以获得更好的性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.