Ve svém volání ajax musíte získat select-box
(názvy tabulek) a pak to musíte přiřadit k nějakému <div>
. Aby to fungovalo, proveďte v kódu níže uvedené změny:
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();
}
Nyní ve vašem somepage.jsp
vložte kód databáze jako níže:
<%@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>');
%>
Do souboru index.jsp stačí přidat <div id="table"></div>
,zde odpověď přijde z somepage.jsp
,také nezapomeňte odstranit další kód ze své stránky index.jsp.