我正在学习如何使用 jquery 自动完成功能,我以 ajax 中的 $.get 方法为例。我看一下http://jqueryui.com/autocomplete/来制作这个例子。
在我的jsp页面中:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>AJAX calls using Jquery in Servlet</title>
<link rel="stylesheet" href="jquery-ui.css" />
<script src="jquery-1.9.1.js"></script>
<script src="jquery-ui.js"></script>
<script>
$(function(){
$('#user').autocomplete({
source: function (request, response) {
var username = $('#user').val();
$.get('autocompleteServlet', {user : username}, function(responseText){
$('#welcometext').text(responseText);
var value = [responseText];
response(value);
});
}
});
});
</script>
</head>
<body>
<form id="form1">
<h1>AJAX Demo using Jquery in JSP and Servlet</h1>
Enter your Name: <input type="text" id="user" /> <input type="button"
id="submit" value="Ajax Submit" /> <br />
<div id="welcometext"></div>
</form>
</body>
</html>
在小服务程序中:
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String value = request.getParameter("user");
System.out.println("user : "+ value);
try {
Connection cnn = XJdbc.getConnection();
String sql = "SELECT Name FROM reported_tasks WHERE Name LIKE '%"+ value + "%'";
Statement stm = cnn.createStatement();
ResultSet rs = stm.executeQuery(sql);
String result = "";
while (rs.next()) {
result = result + rs.getString("Name") + ",";
}
cnn.close();
System.out.println("Request :" + result);
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().print(result);
} catch (Exception e) {
System.out.println("Error : " + e.getMessage());
}
}
我认为问题在于如何将 ajax 响应作为 javascript 的数组类型返回。请帮我解决这个问题,谢谢大家