[英]How to populate a droplist with data from database using jsp,servlet,ajax,jquery
友。 我想填充搜索框,它就像一個下拉列表,當用輸入的名字和名字組成用戶的全名時,它會動態填充。 jsp表單有這個搜索框(下拉列表)。 我正在使用ajax,以便當用戶在搜索框中輸入名稱時,我可以動態顯示包含所有用戶全名的ArrayList。 我對ajax或jquery完全不熟悉。 請指導我從servlet傳遞arrayList數據作為對ajax或jquery腳本的響應,並異步填充下拉列表。 請幫忙
這是我的servlet代碼
@WebServlet("/someservlet/*")
public class AjaxExampleServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Database connection
try {
Connection currentCon = ConnectionManager.getConnection();
currentCon.setAutoCommit(true);
ResultSet rs;
Statement stmt = null;
stmt = currentCon.createStatement();
//create the query
String query = "select firstname,lastname,username from users";
//executing the query
rs = stmt.executeQuery(query);
//creating a hashmap
ArrayList<String> UserFullName = new ArrayList<String>();
//fill the hashmap UserFullName with firstname and lastname of the user fetched from the database
while(rs.next())
{
UserFullName.add(rs.getString("firstname") + rs.getString("lastname"));
}
response.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8");
request.setAttribute("list", UserFullName);
RequestDispatcher requestDispatcher = request.getRequestDispatcher("response.jsp");
requestDispatcher.forward(request, response);
和我的第一個jsp頁面
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<form action="someservlet" method="get">
<button type="submit" id="somebutton">press here</button>
</form>
</body>
</html>
和我的response.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<button id="somebutton">press here</button>
<div id="somediv">
<label for="users">Users</label>
<select id="users" multiple="multiple">
<c:forEach var="listvar" items="${list}">
<option value="${listvar}">${listvar}</option>
</c:forEach>
</select>
</div>
</body>
</html>
我希望我的響應在第一個jsp頁面的同一個jsp中,其中使用ajax,jquery直接搜索到搜索下拉列表的用戶。 歡迎舉例。 請幫朋友。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.