<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
GetByJquery("#area", 0);
$("#area").change(function () {
GetByJquery("#subarea", $("#area").val());
});
$("#btnGet").click(function () {
alert($("#area").val() + "--" + $("#area option:selected").text());
});
});
function GetByJquery(ddlId, id, selId) {
$.getJSON("SelectAjax.ashx", { action: "area", id: id, rnd: Math.random() }, function (data) {
$(ddlId).empty();
$("<option value="-1">不限</option>").appendTo($(ddlId));
$.each(data, function (i, item) {
$("<option></option>")
.val(item.AreaID)
.attr("selected", item.AreaID == selId)
.text(item.AreaName)
.appendTo($(ddlId));
});
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<select id="area" name="area">
<option value="-1">不限</option>
</select>
<select id="subarea" name="subarea">
<option value="-1">不限</option>
</select>
<input id="btnGet" name="btnGet" type="button" value="Get" />
</div>
</form>
</body>
</html>
SelectAjax.ashx文件:
/// <summary>
/// SelectAjax 的摘要说明
/// </summary>
public class SelectAjax : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string action = context.Request.QueryString["action"];
if (("area").Equals(action))
{
string id = context.Request.QueryString["id"];
if (!string.IsNullOrEmpty(id))
context.Response.Write(GetArea(id));
else context.Response.Write("");
}
}
private string GetArea(string id)
{
List<Area> areaList = new List<Area>();
if (id == "0")
{
areaList.Add(new Area
{
AreaID = "01",
AreaName = "罗湖区",
PID = "0"
});
areaList.Add(new Area
{
AreaID = "02",
AreaName = "福田区",
PID = "0"
});
}
if (id == "01")
{
areaList.Add(new Area
{
AreaID = "0101",
AreaName = "莲塘",
PID = "01"
});
areaList.Add(new Area
{
AreaID = "0102",
AreaName = "黄贝岭",
PID = "01"
});
}
if (id == "02")
{
areaList.Add(new Area
{
AreaID = "0201",
AreaName = "八卦岭",
PID = "02"
});
areaList.Add(new Area
{
AreaID = "0202",
AreaName = "华强",
PID = "02"
});
}
return Serialize(areaList);
}
/// <summary>
/// Json序列化
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="t">泛型</param>
/// <returns>序列化</returns>
private string Serialize(object obj)
{
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(obj);
}
/// <summary>
/// Json反序列化
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="strJson">泛型</param>
/// <returns>反序列化</returns>
private T Deserialize<T>(string strJson)
{
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Deserialize<T>(strJson);
}
public class Area
{
public string AreaID { get; set; }
public string AreaName { get; set; }
public string PID { get; set; }
}
public bool IsReusable
{
get
{
return false;
}
}
}