【发布时间】:2014-01-03 04:52:11
【问题描述】:
我有一些值的下拉列表,如果我基于该值更改这些值,将通过替换第一个下拉列表下方的文本来显示另一个带有 mysql 数据库值的下拉列表。我在 jsp 页面中执行此过程。第二个下拉-down 值来自第一个下拉列表的更改事件时的数据库。我的数据库包含两个表,一个用于国家,另一个用于城市。国家表包含字段 countryid 和 country_name,城市表包含字段 cityid、countryid 和 city_name。下面是我到目前为止所做的代码。在这里我需要实现 ajax 和 jquery 吗?您能否给我 fetchCites servlet 代码的代码,以便在不使用任何 php 或 .net 页面的情况下填充第二个下拉列表。
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<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);
}
}
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','fetchCites.do?countryid=' + country_id);
}
</script>
</head>
<body>
<h1>Hello World!</h1>
<FORM NAME="myform">
<SELECT NAME="country" onChange="getCityDropdown()">
<OPTION VALUE="1">India</option>
<OPTION VALUE="2">England</option>
</SELECT>
</FORM>
<div id="second_dropdown_code">This text will be replaced by second City dropdown.
</div>
</body>
</html>
【问题讨论】: