Dalam panggilan ajax Anda, Anda perlu mendapatkan select-box
(nama tabel) dan kemudian Anda perlu menetapkannya ke beberapa <div>
. Lakukan perubahan di bawah ini pada kode Anda untuk membuatnya berfungsi:
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();
}
Sekarang di somepage.jsp
. Anda masukkan kode database Anda seperti di bawah ini :
<%@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>');
%>
Di index.jsp Anda, cukup tambahkan <div id="table"></div>
, di sini respons akan datang dari somepage.jsp
, juga jangan lupa untuk menghapus kode tambahan dari halaman index.jsp Anda.