如何在 jsp 和 ajax 中为两个选择选项框动态地从 mysql 获取和填充值到 HTML 选择选项

Posted

技术标签:

【中文标题】如何在 jsp 和 ajax 中为两个选择选项框动态地从 mysql 获取和填充值到 HTML 选择选项【英文标题】:How to fetch and populate values from mysql to HTML select options dynamically in jsp and ajax for two select option box 【发布时间】:2019-10-07 14:12:12 【问题描述】:

我在从 mysql 数据库获取数据并使用 ajax 将其填充到 html 选择选项时遇到问题。它为第一个选择框正确显示的值,但对于第二个选择框,它显示第一个文本框的内容以及第二个文本框的结果。请帮我在下面的代码中找到问题。我没有使用任何框架。其简单的jsp、ajax和mysql的dynamicweb项目。

尝试了许多可能的解决方案

这是我的代码

<%@page import="java.sql.ResultSetMetaData"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Generic CRUD Home</title>

<script>
    var request;
    function sendSchema() 
        var schemaOption = document.getElementById('schemaName');
        var selectedSchema = schemaOption.options[schemaOption.selectedIndex].value;
        var url = "index.jsp?schema=" + selectedSchema;

        if (window.XMLHttpRequest) 
            request = new XMLHttpRequest();
         else if (window.ActiveXObject) 
            request = new ActiveXObject("Microsoft.XMLHTTP");
        

        try 
            request.onreadystatechange = getTableList;
            request.open("GET", url, true);
            request.send();
         catch (e) 
            alert("Unable to connect to server");
        
    

    function getTableList() 
        if (request.readyState == 4) 
            var tablesList = request.responseText;
            document.getElementById('tableName').innerHTML = tablesList;
            console.log('tablesList :' + tablesList);
            console.log('tablesListXML :' + tablesListXML);
            var tablesListXML = request.responseXML.getElementsById('tableName');
            console.log('tablesListXML :' + tablesListXML);
        
    
    //  var xmlhttp;
    //  function sendTable() 
    //      var tableOption = document.getElementById('tableName');
    //      var selectedTable = tableOption.options[tableOption.selectedIndex].value;
    //      var url = "index.jsp?table=" + selectedTable;

    //      if (window.XMLHttpRequest) 
    //          xmlhttp = new XMLHttpRequest();
    //       else if (window.ActiveXObject) 
    //          xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    //      

    //      try 
    //          xmlhttp.onreadystatechange = getTableContents;
    //          xmlhttp.open("GET", url, true);
    //          xmlhttp.send();
    //       catch (e) 
    //          alert("Unable to connect to server");
    //      
    //  

    //  function getTableContents() 
    //      if (xmlhttp.readyState == 4) 
    //          var tableContents = xmlhttp.responseXML;
    //          document.getElementById('tableContent').innerHTML = tableContents;
    //      
    //  
</script>
</head>
<body>
    <h1>Generic CRUD Home</h1>

    <%
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
        Statement stmtSchemaList = conn.createStatement();
        Statement stmtTableLit = null;
        ResultSet rsSchemaList = stmtSchemaList.executeQuery("show databases");
        ResultSet rsTableList = null;
        ResultSetMetaData rsmd = null;
    %>
    Database/Schema Name :
    <select id="schemaName" onchange="sendSchema()">
        <option value="null" selected="selected">Select
            Database/Schema</option>
        <%
            while (rsSchemaList.next()) 
                out.println(
                        "<option value=" + rsSchemaList.getString(1) + ">" + rsSchemaList.getString(1) + "</option>");
            
            rsSchemaList.close();
            if (request.getParameter("schema") != null) 
                String selectedSchema = request.getParameter("schema");
                stmtTableLit = conn.createStatement();
                stmtTableLit.execute("use " + selectedSchema);
                PreparedStatement pstmt = conn.prepareStatement("show tables");
                rsTableList = pstmt.executeQuery();

            
        %>
    </select> Table :
    <select id="tableName" onchange="sendTable()">
        <option value="null" selected="selected">Choose the Table</option>
        <%
            if (rsTableList != null) 
                while (rsTableList.next()) 
                    out.println(
                            "<option value=" + rsTableList.getString(1) + ">" + rsTableList.getString(1) + "</option>");
                
                rsTableList.close();
            
        %>
    </select>

    <div id="tableContent">
        <table border="0">
        </table>
    </div>
</body>
</html>

我得到的输出是

输出我运行此代码时得到的结果

【问题讨论】:

您的代码中有多个问题。你应该得到表名 onChange of shema selected。 【参考方案1】:

在您的 ajax 调用中,您需要获取 select-box(表名),然后您需要将其分配给一些 &lt;div&gt; 。在您的代码中进行以下更改以使其正常工作:

javascript:

function sendSchema() 
        var schemaOption = document.getElementById('schemaName');
        var selectedSchema = schemaOption.options[schemaOption.selectedIndex].value;
        var url = "somepage.jsp?schema=" + selectedSchema;

        if (window.XMLHttpRequest) 
            request = new XMLHttpRequest();
         else if (window.ActiveXObject) 
            request = new ActiveXObject("Microsoft.XMLHTTP");
        

         request.onreadystatechange= function() 
                        
                            if(this.readyState === 4 && this.status === 200) 
                            document.getElementById("table").innerHTML =this.responseText;// getting response and assign to div with id->table
                        
                    ; 
                        request.open("GET",url,true);  
                        request.send();
    

现在在您的somepage.jsp 中输入您的数据库代码,如下所示:

<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>


     <%
          Statement stmtTableLit = null;
          ResultSet rsTableList = null;
      Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");

     if (request.getParameter("schema") != null) 
                    String selectedSchema = request.getParameter("schema");//getting data 
                    stmtTableLit = conn.createStatement();
                    stmtTableLit.execute("use " + selectedSchema);
                    PreparedStatement pstmt = conn.prepareStatement("show tables");
                    rsTableList = pstmt.executeQuery();

                
   //whatever will be  there in out.println() will be sent back as response to your index.jsp page         
       out.println('<select id="tableName" onchange="sendTable()">
            <option value="null" selected="selected">Choose the Table</option>');

                if (rsTableList != null) 
                    while (rsTableList.next()) 
                        out.println(
                                "<option value=" + rsTableList.getString(1) + ">" + rsTableList.getString(1) + "</option>");
                    
                    rsTableList.close();
                

        out.println('</select>');
     %>

在您的 index.jsp 中,只需添加一个 &lt;div id="table"&gt;&lt;/div&gt; ,这里的响应将来自 somepage.jsp ,也不要忘记从您的 index.jsp 页面中删除额外的代码。

【讨论】:

以上是关于如何在 jsp 和 ajax 中为两个选择选项框动态地从 mysql 获取和填充值到 HTML 选择选项的主要内容,如果未能解决你的问题,请参考以下文章

J2EE 两个list如何在JSP页面中交替输出?

如何在codeigniter中将ajax选择的依赖下拉选项传递给mysql数据库

如何在引导选择选择器中为选项(下拉菜单)设置固定宽度

如何在 Flutter 中为未选择的选项卡添加下划线?

如何使用 jquery 或 ajax 在 c#/asp.net 中为 MVC 项目更新 razor 部分视图

如何在角度6中为选择选项设置默认选定对象