0
我希望有人能指導我在正確的方向。我想要做的是創建兩個下拉列表,其中第二個(城市)取決於第一個(州)。例如,當我點擊華盛頓時,我想要第二個下拉菜單列出西雅圖和Walla Wallal;格魯吉亞,亞特蘭大,雅典等等。最終我的目標是將幾個列表連接起來(國家 - >州 - >縣 - >城市),但如果我能夠使這兩個工作,我想我可以找出如何做到這一點。動態下拉列表與AJAX和數據庫
到目前爲止,我有兩個數據庫的設置。具有cityid(主)和cityname作爲列的TABLE CITY和具有stateid(主)和州名作爲列的表STATE。
代碼如下
dropDown.jsp:
<script>
function createRequestObject(){
var req;
if(window.XMLHttpRequest){
//For Firefox, Safari, Opera
req = new XMLHttpRequest();
} else if(window.ActiveXObject){
//For IE 5+
req = new ActiveXObject("Microsoft.XMLHTTP");
} else {
//Error for an old browser
alert('Your browser is not IE 5 or higher, or Firefox or Safari or Opera');
}
return req;
}
//Make the XMLHttpRequest Object
var http = createRequestObject();
function sendRequest(method, url){
if(method == 'get' || method == 'GET'){
http.open(method,url);
http.onreadystatechange = handleResponse;
http.send(null);
}
}//end function send
function handleResponse(){
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
document.getElementById("second_dropdown_code").innerHTML = response;
}
}
}
function getCityDropdown() {
var w = document.myform.mylist.selectedIndex;
var country_id = document.myform.mylist.options[w].value;
sendRequest('GET','getCites.do?stateid=' + state_id);
}
</script>
<FORM NAME="myform">
<SELECT NAME="state" onChange="getCityDropdown()">
<OPTION VALUE="1">Georgia</option>
<OPTION VALUE="2">Washington</option>
</SELECT>
</FORM>
<div id="second_dropdown_code"></div>
getCities.java
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
processRequest(request, response);
String sql = "select * from CITY";
Connection connection = datasource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(sql);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
//out.println(resultSet.getInt("cityid") + "<br/>" + resultSet.getString("city") + "<br/>" + resultSet.getString("INSTRUCTOR") + "<br/>" + resultSet.getString("BUILDING") + "<br/>" + resultSet.getString("ROOM") + "<br/>");
//out.println(resultSet.getInt("cityid") + "<br/>" + resultSet.getString("city") + "<br/>");
//out.println("<select name=\"city\"><option value=\"1\">Atlanta</option><option value=\"2\">Walla Walla</option></select> ");
}
resultSet.close();
preparedStatement.close();
connection.close();
} catch (SQLException ex) {
Logger.getLogger(getCities.class.getName()).log(Level.SEVERE, null, ex);
}
}
我知道我需要某種如果在while循環語句的,但我不確定我從哪裏獲取參數來比較stateid和cityid。
任何指導都會受到影響,謝謝。
你問如何獲得來自jsp頁面的參數並在servlet sql查詢中使用該值? – user75ponic