就以選取省份後改變城市選項為例,省份、城市數據存放於後台MSSQL Server,就一個表:Citys:字段State、City。
程序:
CitySelect.ASP
<%@ LANGUAGE="vbscript" %>
<%
strPathInfo = Request.ServerVariables("PATH_INFO")
strPathInfo = "http://" & Request.ServerVariables("SERVER_NAME") & Left(strPathInfo,InstrRev(strPathInfo,"/"))
Set Conn = Server.CreateObject("ADODB.Connection")
Conn.Provider = "sqloledb"
Conn.Open "Data Source=ServerName;Initial Catalog=dbName;", "sa", ""
Set RS = Conn.Execute("SELECT DISTINCT state FROM citys")
arrPr = RS.GetRows()
RS.Close
Set RS = Nothing
Conn.Close
Set Conn = Nothing
%>
<Html>
<HEAD>
<META http-equiv="Content-Type" content="text/Html; charset=gb_2312-80">
<TITLE></TITLE>
<SCRIPT language=Javascript>
<!--
function ChooseCity()
{
file://Clear City List
for(var i=form1.SelCity.options.length-1;i>=0;--i)
{
form1.SelCity.options.remove(i)
}
var sState = form1.SelState.options(form1.SelState.selectedIndex).value;
var oXMLDoc = new ActiveXObject('MSXML');
sURL = '<%=strPathInfo%>XMLCity.ASP?State=' + sState;
oXMLDoc.url = sURL;
var oRoot=oXMLDoc.root;
if(oRoot.children != null)
{
for(var i=0;i<oRoot.children.length;++i)
{
oItem = oRoot.children.item(i);
sName = oItem.text;
var oOption = document.createElement('OPTION');
oOption.text = sName;
oOption.value = sName;
form1.SelCity.options.add(oOption);
}
}
}
-->
</SCRIPT>
</HEAD>
<BODY>
<FORM action="" method="post" id="form1" name="form1">
<SELECT name="SelState" id="SelState" onchange="ChooseCity()">
<%For i = LBound(arrPr,2) To UBound(arrPr,2)%>
<OPTION value="<%=arrPr(0,i)%>"><%=arrPr(0,i)%></OPTION>
<%Next%>
</SELECT>
<SELECT name="SelCity" id="SelCity">
</SELECT>
</FORM>
</BODY>
</Html>
--------------------------
XMLCity.ASP
<%@ LANGUAGE="VBSCRIPT" %>
<%
sState = Request.QueryString("State")
Set Conn = Server.CreateObject("ADODB.Connection")
Conn.Provider = "sqloledb"
Conn.Open "Data Source=ServerName;Initial Catalog=dbName;", "sa", ""
Set RS = Conn.Execute("SELECT city FROM citys WHERE state='" & sState & "'")
arrCity = Rs.GetRows()
%>
<?XML version="1.0" encoding="gb2312" ?>
<citys>
<%For i = LBound(arrCity,2) To UBound(arrCity,2)%>
<city><%=arrCity(0,i)%></city>
<%Next%>
</citys>
--------------------------
幾點說明:
1、簡單的說,這種方法就是利用客戶端MSXMl對象去load一個xml,而這個XML文件的後綴是ASP,呵呵,傳個querysting過去就可以為所欲為了,好處是顯然的:頁面不刷新;傳輸的數據少,不需要把所有數據全傳到客戶端 :)
2、這種方法Zee最早是在White前輩的一篇帖子裡看到的,不過他老人家的sample是用來取服務器端的時間,大材小用阿。 :P
3、本方法對IE4以上版本有效。(這也是為什麼不用"microsoft.XMLDOM"對象而用"msXML"的原因)