根据选项(下拉)选择动态更新SQL Select查询和HTML结果

时间:2019-01-30 19:50:48

标签: jquery sql ajax jsp

我有一个JSP页面,该页面发出选择查询以填充表中所有标题的下拉列表/选项框。我想用从下拉/选项框中选择的ID和标题动态更新h1标记(仅当值更新时)。

现在,我要动态更改的元素已被注释掉,并且我添加了一些JQuery来标识下拉列表/选项框的值何时更改。

<%@ page import="java.sql.*"%>
<html>
<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            $('#select').on('change',function ()
            {
            alert($('#select').find(":selected").val());
            });
        });
    </script>
</head>

<body>
<h1>JDBC Connection example</h1>

<%
  String db = "jdbc:mysql://localhost/db";
  String user = "admin";
  String pass = "pass";

  try {
    java.sql.Connection con;
    java.sql.Statement statement;
    java.sql.ResultSet resultSet;
    Class.forName("com.mysql.cj.jdbc.Driver");
    con = DriverManager.getConnection(db,user,pass);

    statement = con.createStatement();
    String sql ="SELECT * FROM titles";
    resultSet = statement.executeQuery(sql);
%>

<!-- I want the query to display an updated title and id each time the dropdown is changed
<h1><%=resultSet.getString("id")%></h1>
<h1><%=resultSet.getString("title")%></h1>
-->


<h1>Drop down box</h1>
<select id="select">
<% while(resultSet.next()){ %>
    <option value='<%= resultSet.getString("id")%>'><%= resultSet.getString("title")%></option>
<% } %>
</select>


<%
}catch(Exception e){
    out.println("wrong entry"+e);
}
%>
</body>
</html>

0 个答案:

没有答案