這裡用 Ajax 技術實現一個經典的省市聯動下拉框。頁面其實仍然發生着「刷新」,只是所有工作都在後台異步完成,快到我們察覺不到——這正是 Ajax 犧牲一部分頁面資源換取流暢體驗的體現。
AjaxPro.dll 可從官網下載。使用前需在 Web.config 中註冊 httpHandler:
<httpHandlers>
<add verb="POST,GET" path="ajaxpro/*.ashx"
type="AjaxPro.AjaxHandlerFactory, AjaxPro.2"/>
</httpHandlers>
頁面上放置兩個下拉框 DropDownList1(省份)與 DropDownList2(城市)。當省份選擇變化時,areaResult 函數取得當前值並調用後台方法 GetCityList,結果通過 get_city_Result_CallBack 回調處理:
function areaResult() {
var area = document.getElementById("DropDownList1");
AjaxTest.GetCityList(area.value, get_city_Result_CallBack);
}
function get_city_Result_CallBack(response) {
if (response.value != null) {
document.all("DropDownList2").length = 0;
var ds = response.value;
if (ds != null && typeof(ds) == "object" && ds.Tables != null) {
for (var i = 0; i < ds.Tables[0].Rows.length; i++) {
var name = ds.Tables[0].Rows[i].name;
var id = ds.Tables[0].Rows[i].id;
document.all("DropDownList2").options.add(new Option(name, id));
}
}
}
}
後端在 Page_Load 中通過 AjaxPro.Utility.RegisterTypeForAjax 註冊本頁類型,並在首次加載時綁定省份數據、為 DropDownList1 掛上 onchange 事件。真正提供數據的方法用 [AjaxPro.AjaxMethod] 標記,根據傳入的省份 id 查詢對應城市並返回 DataSet:
[AjaxPro.AjaxMethod]
public DataSet GetCityList(int id) {
string sql = "select name from test where id='" + id + "'";
return GetDataSet(sql, "test");
}
需要提醒的是,示例中直接拼接 SQL 存在注入風險,實際項目應改用參數化查詢。整體而言,借助 AjaxPro 我們可以用極少的代碼實現流暢的聯動下拉框體驗。