这里是以省份和城市为例,由于用到数据库,请先建立数据库dlist.mdb
数据库名称:dlist.mdb
省份表名称:province
字段有:p_id(类型:自动编号),p_name(类型:文本,省份名称)
城市表名称:city
字段有:c_id(类型:自动编号),c_pid(类型:文本,省份名称,等于province表中的p_name),c_name(类型:文本,城市名称)
源程序如下,保存为asp文件即可执行。
————————————————————
<%
dim id
id=request.querystring("id")
if id="1" then
response.write "<br>" & request.form("lstb")
response.write "<br>" & request.form("lsts")
end if
%>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
<title>js动态列表示例</title>
<script language="javascript">
<!–
var ssort = new array();
var num = 0;
<%
dim conn,rs,grs,i,j,pstr
pstr=""
set conn=server.createobject("adodb.connection")
set rs=server.createobject("adodb.recordset")
set grs=server.createobject("adodb.recordset")
conn.open "provider=microsoft.jet.oledb.4.0;data source=" & server.mappath("dlist.mdb")
写省份js数组
rs.open "select * from province;",conn,1,1
for i=0 to rs.recordcount-1
pstr=pstr & "<option value=""" & rs("p_name") & """>" & rs("p_name") & "</option>"
getsub(rs("p_name"))
rs.movenext
next
rs.close()
set rs=nothing
set grs=nothing
根据省份写城市js数组的过程
sub getsub(pname)
grs.open "select * from city where c_pid=" & pname & ";",conn,1,1
for j=1 to grs.recordcount
response.write "ssort[num++] = new array(""" & grs("c_name") & """ ,""" & pname & """);" & vbcrlf
grs.movenext
next
grs.close()
end sub
%>
var nssortcount = num;
function sdbsortchange(cmbsdbsort, cmbssort)
{
var nselsdbsort = cmbsdbsort.selectedindex;
var ssdbsort = cmbsdbsort.options[nselsdbsort].value;
cmbssort.length = 0;
cmbssort.options[0] = new option(-请选择-, );
for(var i=0; i<nssortcount; i++)
{
if(ssort[i][1] == ssdbsort)
{
cmbssort.options[cmbssort.length] = new option(ssort[i][0], ssort[i][0]);
}
}
}
function initssort(cmbsdbsort, cmbssort)
{
var nselsdbsort = cmbsdbsort.selectedindex;
var ssdbsort = cmbsdbsort.options[nselsdbsort].value;
var sssort = cmbssort.options[0].value;
cmbssort.length = 0;
cmbssort.options[0] = new option(-请选择-, );
var n = 0;
for(var i=0; inssortcount; i++)
{
if(ssort[i][1] == ssdbsort)
{
cmbssort.options[cmbssort.length] = new option(ssort[i][0], ssort[i][0]);
if(ssort[i][0] == sssort)
cmbssort.options[cmbssort.length-1].selected = true;
}
}
}
//–>
</script>
</head>
<body>
<p> </p>
<p> </p>
<p> </p>
<form action="index.asp?id=1" method="post" name="frmdlist" id="frmdlist">
<table width="408" border="0" align="center" cellpadding="2" cellspacing="2">
<tr>
<td width="400" align="center">js动态列表示例</td>
</tr>
<tr>
<td align="center"><%response.write "<select name=""lstb"" style=""width:200"" onchange=""sdbsortchange(this,frmdlist.lsts);"">" & pstr & "</select>"%>
</td>
</tr>
<tr>
<td align="center"> </td>
</tr>
<tr>
<td align="center"><select style="width:200" name="lsts" id="lsts">
</select>
</td>
</tr>
</table>
<p align="center">
</p>
<p align="center"> </p>
<p align="center">
<input type="submit" name="submit" value="提交">
</p>
</form>
</body>
</html>