我希望有人能引导我朝着正确的方向前进。我要做的是创建两个下拉列表,其中第二个(城市)取决于第一个(州)。例如,当我点击华盛顿时,我希望第二个下拉菜单列出西雅图和沃拉沃拉;乔治亚州、亚特兰大、雅典等。最终我的目标是将几个列表链接在一起(国家 -> 州 -> 县 -> 城市),但如果我能让这两个工作正常,我想我可以弄清楚如何做到这一点。
到目前为止,我已经建立了两个数据库。表 CITY 以 cityid (primary) 和 cityname 作为列,表 STATE 以 stateid (primary) 和 statename 作为列。
代码如下
下拉.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>
获取城市.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 循环中使用某种 if 语句,但我不确定从哪里获取参数以将 stateid 与 cityid 进行比较。
任何指导将不胜感激,谢谢。