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

查看:74
本文介绍了如何在jsp和ajax中为两个选择选项框动态地从mysql取值和填充值到HTML选择选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm facing a problem while fetching the data from MySQL database and populating it to html select option using ajax. 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.

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

Tried many possible solutions

这是我的代码

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

我得到的输出是

输出运行此代码时得到的信息

推荐答案

在ajax调用中,您需要获取select-box(表名),然后将其分配给某些<div>.在代码中进行以下更改以使其起作用:

In your ajax call you need to get the select-box(table names) and then you need to assign that to some <div> . Do below changes in your code to make it work :

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中,将您的数据库代码如下:

Now in your somepage.jsp put your database code like below :

<%@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中,只需添加一个<div id="table"></div>,这里的响应将来自somepage.jsp,也不要忘记从index.jsp页面中删除多余的代码.

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 .

这篇关于如何在jsp和ajax中为两个选择选项框动态地从mysql取值和填充值到HTML选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆