简体   繁体   English

如何在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

I'm facing a problem while fetching the data from MySQL database and populating it to html select option using ajax. 我在从MySQL数据库获取数据并使用ajax将其填充到html选项时遇到问题。 The value it is displaying properly for first select box, but for the second select box, it is displaying the content of first text box as well as result of second text box. 它为第一个选择框正确显示的值,但对于第二个选择框,它显示第一个文本框的内容以及第二个文本框的结果。 Please help me to find the problem in the below code. 请帮我在下面的代码中找到问题。 I'm not using any framework. 我没有使用任何框架。 Its simple jsp, ajax and mysql dynamicweb project. 它简单的jsp,ajax和mysql dynamicweb项目。

Tried many possible solutions 试过很多可能的解决方案

Here is my code 这是我的代码

<%@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>

The output i'm getting is 我得到的输出是

Output what i'm getting when i run this code 输出我运行此代码时得到的内容

在此输入图像描述

In your ajax call you need to get the select-box (table names) and then you need to assign that to some <div> . 在你的ajax调用中,你需要获取select-box (表名),然后你需要将它分配给某些<div> Do below changes in your code to make it work : 在代码中进行以下更改以使其正常工作:

Javascript : 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();
    }

Now in your somepage.jsp put your database code like below : 现在在你的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>');
     %>

In your index.jsp ,just add a <div id="table"></div> ,here response will come from somepage.jsp ,also don't forget to remove extra code from your index.jsp page . 在你的index.jsp中,只需添加一个<div id="table"></div> ,这里的响应将来自somepage.jsp ,也不要忘记从index.jsp页面中删除额外的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM