一直以来都有个想法就是把以前学过的用过的东西整理下,为了方便查找。可是不知从何下手。今天终于下定决心开始我的每一篇blog.
用AJAX与XML, 实现无刷新的二级联动下拉列表
第一步,创建html文件包含二个下拉列表与AJAX
<html>
<head>
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无刷新的二级联动下拉列表</title>
<script language="JavaScript">
function change(x)
{
var temp1 = document.form1.A2;
//册除A2的下拉列表
for (var kk = temp1.options.length-1; kk > 0; kk--)
temp1.options[kk] = null;
var objXmlHTTP = new ActiveXObject("Microsoft.XMLHTTP");
// timestamp:加时间防止IE数据缓存不能实时更新
objXmlHTTP.open("get","GetA2XML.asp? A1="+escape(x)+" &timeStamp="+new Date().getTime() ,true);
objXmlHTTP.send("");
objXmlHTTP.onreadystatechange=function()
{
if (objXmlHTTP.readystate==4)
{
var objXmlDOM=objXmlHTTP.ResponseXML
//解析xml
var objlst = objXmlDOM.getElementsByTagName("item ");
//动态创建A2下拉列表
for (var tt= 0;tt < objlst.length; tt++)
temp1.options[tt+1] = new Option(objlst.item(tt). childNodes(0).text, objlst.item(tt) .childNodes(1).text);
}
}
}
</script>
</head>
<body>
<form name="form1" action="xx.asp" method="post" onSubmit="javascrip: return CheckForm()">
<table width="90%" border="0" cellspacing="1" cellpadding="2" align="center">
<tr>
<td>
<select name="A1" onClick="change(this.value)">
<option value="1">11</option>
<option value="2">22</option>
<option value="3">33</option>
</select>
</td>
<td><select name="A2" ></select></td>
</tr>
<tr><td align="center" colspan="2"><input type="submit" value="" style="width:10%"></td></tr>
</table>
</form>
</body>
</html>
第二步,创建Server端的处理程序.返回xml数据(可用asp,asp.net,php等),以下是asp实现
<!--#include file="../inc/userconn.asp" -->
<%
Response.expires = 0
Response.CharSet="utf-8"
Response.ContentType="text/xml"
dim conn, rs, sql, strXML, A1
A1 = trim(request("A1")
if A1 = "" then
sql = "Select * FROM A1 where A1='"&A!&"'"
end if
set rs=server.CreateObject("ADODB.Recordset")
rs.open sql,conn,1,1
if rs.eof and rs.bof then
response.End()
end if
strXML = "<?xml version=""1.0"" encoding=""utf-8""?>"
strXML = strXML & "<data>"
do while not rs.eof
strXML = strXML & "<item>"
//xml文件加cdata是为了过滤特殊符号
strXML = strXML & "<ID><![CDATA["&rs("ID")&"]]></ID>"
strXML = strXML & "<text><![CDATA["&rs("text")&"]]></text>"
strXML = strXML & "</item>"
rs.movenext
loop
strXML = strXML & "</data>"
rs.close
set rs = nothing
conn.close
set conn = nothing
response.Write strXML
%>
注意此asp文件必须以utf-8的文件格式存储,如果是多语言可能出现乱码。