提前致谢。 我有一个自动完成输入字段,我们可以在其中键入字符串并使用jquery自动完成我从JSP页面获取下拉列表,JSP页面调用Java函数从MYSQL中检索数据。
HTML代码如下。
<form>
<input type="hidden" id="autosuggest" name="autosuggest" value="Y"/>
<input type="text" name="Category" id="searchp" value="">
<script>
$("#searchp").autocomplete({
delay: 100,
autoFocus: true,
selectFirst: true,
source: 'ProviderSuggest.jsp',
select: function (event, ui) {
$('#autosuggest').val('Y');
}
});
</script>
<input type="submit" value="Submit"/>
</form>
以下是ProviderSuggest.jsp的代码
<%@page import="java.util.Map"%>
<%@page import="java.util.HashMap"%>
<%@page import="com.google.gson.Gson"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.Iterator"%>
<%@page import="Functions.DBConnections"%>
<%@page import="java.util.List"%>
<%
String query = request.getParameter("term");
List<String> CategoryList = new DBConnections().GetCategoryList(query);
Iterator CatIterator = CategoryList.iterator();
String JCategory = "";
Map CategoryMap = new HashMap();
while (CatIterator.hasNext()) {
String Category = (String) CatIterator.next();
String CategoryID = (String) CatIterator.next();
CategoryMap.put(CategoryID, Category);
}
Gson gson = new Gson();
JCategory = gson.toJson(CategoryMap);
System.out.println(JCategory);
//out.print(JCountry);
out.print(JCategory);
%>
以下是Java函数从MySql获取数据的代码
public static List GetCategoryList(String Keyword) {
List<String> CategoryList = new ArrayList<String>();
try {
Class.forName(driverName).newInstance();
Connection connection = DriverManager.getConnection(connectionURL + dbName, dbuserID, dbpwd);
PreparedStatement preStatement;
ResultSet resultSet;
String query = "SELECT Category, CategoryID FROM category WHERE Keywords LIKE '%" + Keyword + "%' AND ParentCatID != 0 Limit 10";
preStatement = connection.prepareStatement(query);
resultSet = preStatement.executeQuery(query);
while (resultSet.next()) {
CategoryList.add(resultSet.getString(1));
CategoryList.add(resultSet.getString(2));
}
resultSet.close();
preStatement.close();
connection.close();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {
Logger.getLogger(DBConnections.class.getName()).log(Level.SEVERE, null, ex);
}
return CategoryList;
}
如果您看到ProviderSuggest.jsp正在返回具有CategoryID和Category的数组。 当我在前端显示它时,我能够显示Category,我试图将该自动完成输入字段的值设置为CategoryID,这样当我提交表单时,我只发送类别ID进行进一步处理。 我可以知道我在做什么错,因为我无法将输入字段的值设置为CategoryID。
感谢。