```
2. ashx 處理程序代碼(省份列表.ashx):
```csharp<%@ WebHandler Language="C#" Class="ProvinceList" %>using System;
using System.Web;
using System.Web.Script.Serialization;
public class ProvinceList : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "application/json";
var provinces = new [] {
new { id = 1, name = "廣東省" },
new { id = 2, name = "北京市" },
// 其他省份...
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(provinces);
context.Response.Write(json);
}
public bool IsReusable {
get {
return false;
}
}
}
```
3. ashx 處理程序代碼(城市列表.ashx):
```csharp<%@ WebHandler Language="C#" Class="CityList" %>using System;
using System.Web;
using System.Web.Script.Serialization;
public class CityList : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "application/json";
int provinceId = Convert.ToInt32(context.Request.QueryString["provinceId"]);
var cities = GetCitiesByProvinceId(provinceId);
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(cities);
context.Response.Write(json);
}
public bool IsReusable {
get {
return false;
}
}
private object[] GetCitiesByProvinceId(int provinceId) {
switch (provinceId) {
case 1:
return new [] {
new { id = 11, name = "廣州市" },
new { id = 12, name = "深圳市" },
// 其他城市...
};
case 2:
return new [] {
new { id = 21, name = "北京市" },
new { id = 22, name = "朝陽區(qū)" },
// 其他城市...
};
default:
return new object[0];
}
}
}
```
通過以上的示例,可以看到通過 Ajax + ashx 綁定下拉框是一種非常便捷的方式,能夠靈活地實(shí)現(xiàn)動(dòng)態(tài)加載數(shù)據(jù)和級(jí)聯(lián)效果。在實(shí)際開發(fā)中,可以根據(jù)具體需求,通過修改 ashx 處理程序的代碼,獲取不同的數(shù)據(jù)源,并根據(jù)數(shù)據(jù)源的結(jié)構(gòu)進(jìn)行相應(yīng)的數(shù)據(jù)綁定操作。同時(shí),可以根據(jù)需要,添加額外的事件監(jiān)聽和處理邏輯,以滿足更復(fù)雜的應(yīng)用場(chǎng)景。