1、前台部分代码如下:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="js/common.js" type="text/javascript"></script>
<script type="text/javascript">
window.onload = function() {
//创建xmlhttprequest对象
request = createRequest();
getProvince();
setTimeout("getCity()", 50);
}
function getProvince() {
request.open("get", "GetProvince.ashx?pid=-1", true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200) {
//获取响应文本
//把字符串转换成json格式的对象
var json = eval(request.responseText);
var pro = document.getElementById("province");
//遍历json数据
for (var i = 0; i < json.length; i++) {
var option = document.createElement("<option value='" + json[i].Id + "'></option>");
option.innerHTML = json[i].Name;
pro.appendChild(option);
}
}
else {
alert("error");
}
}
}
request.send();
}
function getCity() {
var pro = document.getElementById("province");
request.open("get", "GetProvince.ashx?pid=" + pro.value, true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200) {
var json = eval(request.responseText);
var city = document.getElementById("city");
//清空select中的项
city.innerHTML = "";
//遍历json数据
for (var i = 0; i < json.length; i++) {
var option = document.createElement("<option value='" + json[i].Id + "'></option>");
option.innerHTML = json[i].Name;
city.appendChild(option);
}
}
}
}
request.send();
}
</script>
</head>
<body>
<select id="province" onchange="getCity()">
</select>
<select id="city">
</select>
</body>
</html>
2、后台部分代码如下:
string pid = context.Request.QueryString["pid"];
context.Response.Write(GetProOrCity(pid));
//返回json格式的数据
string GetProOrCity(string pid)
{
List<Province> list = GetPros();
StringBuilder sb = new StringBuilder();
sb.Append("[");
for (int i = 0; i < list.Count; i++)
{
if (list[i].Pid.ToString() == pid)
{
sb.AppendFormat("{{\"Id\":{0},\"Name\":\"{1}\",\"Pid\":{2}}},",list[i].Id,list[i].Name,list[i].Pid);
}
}
//移除最后一项的,
sb.Remove(sb.Length - 1, 1);
sb.Append("]");
return sb.ToString();
}
List<Province> GetPros()
{
List<Province> list = new List<Province>();
list.Add(new Province() { Id=1,Name="河北省",Pid=-1});
list.Add(new Province() { Id = 2, Name = "河南省", Pid = -1 });
list.Add(new Province() { Id = 3, Name = "山东省", Pid = -1 });
list.Add(new Province() { Id = 4, Name = "邯郸市", Pid = 1 });
list.Add(new Province() { Id = 5, Name = "石家庄", Pid = 1 });
list.Add(new Province() { Id = 6, Name = "张家口", Pid = 1 });
list.Add(new Province() { Id = 7, Name = "郑州市", Pid = 2 });
list.Add(new Province() { Id = 8, Name = "开封市", Pid = 2 });
list.Add(new Province() { Id = 9, Name = "安阳市", Pid = 2 });
list.Add(new Province() { Id = 10, Name = "济南市", Pid = 3 });
list.Add(new Province() { Id = 11, Name = "烟台市", Pid =3 });
list.Add(new Province() { Id = 12, Name = "德州市", Pid = 3 });
return list;
}
08-11
08-11
08-11