<html>
<head>
<script type="text/javascript">
//Ajax实现下拉框二级级联,根据第一个下拉框的值改变第二个下拉框内的列表
//根据浏览器的类型,创建xmlHttpRequest对象
function createXmlHttpRequest()
{
if(window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
else if( window.XMLHttpRequest())
{
return new XMLHttpRequest();
}
}
var xmlHttpRequest;
//异步响应函数
function search(para)
{
var url="/search?para="+para; //后台请求的路径
xmlHttpRequest=createXmlHttpRequest();
xmlHttpRequest.onreadystatechange=callback; //将回调函数注册给状态改变事件
xmlHttpRequest.open("GET",url,true);
xmlHttpRequest.send(null);
}
//回调函数
function callback()
{
var dlCity=document.getElementById("city");
//请求被成功响应,已接收到结果
if(xmlHttpRequest.readyState==4&&xmlHttpRequest.status==200)
{
var result=xmlHttpRequest.responseText; //返回的结果字符串
//var result = "哈尔滨|大庆||鹤岗|佳木斯|牡丹江";
var cityArray= result.split("|"); //返回的结果字符串中,值之间是以|分隔的,所以先拆分成数组
var count = cityArray.length;
dlCity.length=0; //先将下拉列表框清空
for (var i = 0; i <count; i++)
{
dlCity.options.add(new Option(cityArray[i], cityArray[i])); //将结果循环添加到下拉列表中
}
}
else
{
dlCity.length=0;
dlCity.options.add(new Option("请等待...","-1"));
}
}
//下拉框改变事件
function changeCityOptions()
{
var dlProvince=document.getElementById("province");
var dlCity=document.getElementById("city");
dlCity.length=0;
if(dlProvince.value==-1)
{
dlCity.options.add(new Option("城市列表","-1"));
}
else
{
search(dlProvince.value);
}
return;
}
</script>
</head>
<body>
<select name="province" id="province" onchange="changeCityOptions()">
<option value="-1">选择省份</option>
<option value="1">黑龙江</option>
<option value="2">吉林</option>
</select>
<select name="city" id="city">
<option value="-1">城市列表</option>
</select>
</body>
</html>