DIV CSS 佈局教程網

用 Ajax 做無刷新三級聯動下拉選單(省/市/區完整實作)
編輯:AJAX基礎知識     

省、市、區三級聯動是表單開發的經典題目。傳統作法是每換一層就 Postback 一次,頁面閃個幾下,捲動位置還會跑掉。改用 Ajax 之後,第二、三層的選項在背景悄悄載入,使用者幾乎感覺不到等待。

實作架構

此範例使用 Ajax.NET Professional 這類「代理映射」型框架,因此後端的方法可以加上 [Ajax.AjaxMethod] 標註,前端就能直接以 AjaxMethod.GetCityList(...) 的形式呼叫,回傳的 DataSet 會被序列化後交給 callback 處理。

前端:三個下拉選單與兩個 callback

頁面放三個 asp:DropDownList,分別綁定 onclick 事件觸發後續載入;另有一個 TextBox 用來顯示目前選到的完整路徑。

// 城市
function cityResult() {
    var city = document.getElementById("DropDownList1");
    AjaxMethod.GetCityList(city.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].city;
                var id   = ds.Tables[0].Rows[i].cityID;
                document.all("DropDownList2").options.add(new Option(name, id));
            }
        }
    }
}

// 市區:寫法與上面完全對稱
function areaResult() {
    var area = document.getElementById("DropDownList2");
    AjaxMethod.GetAreaList(area.value, get_area_Result_CallBack);
}

function get_area_Result_CallBack(response) {
    if (response.value != null) {
        document.all("DropDownList3").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].area;
                var id   = ds.Tables[0].Rows[i].areaID;
                document.all("DropDownList3").options.add(new Option(name, id));
            }
        }
    }
}

// 讀取三層選取值
function getData() {
    var province = document.getElementById("DropDownList1");
    var pValue = province.options[province.selectedIndex].value;
    var pText  = province.options[province.selectedIndex].text;

    var city = document.getElementById("DropDownList2");
    var cValue = city.options[city.selectedIndex].value;
    var cText  = city.options[city.selectedIndex].text;

    var area = document.getElementById("DropDownList3");
    var aValue = area.options[area.selectedIndex].value;
    var aText  = area.options[area.selectedIndex].text;

    document.getElementById("<%=TextBox1.ClientID%>").innerText =
        "省:" + pValue + "|" + pText +
        "市:" + cValue + "|" + cText +
        "區:" + aValue + "|" + aText;
}

三個 callback 的骨架幾乎一致:清空下層選單、檢查回傳的 DataSet 型別、逐列取出名稱與 id 塞進 Option 物件。這正是可以抽成共用函式的地方。

後端:AjaxMethod 類別

public class AjaxMethod
{
    public static DataSet GetProvinceList()
    {
        string sql = "select * from province";
        return GetDataSet(sql);
    }

    [Ajax.AjaxMethod(Ajax.HttpSessionStateRequirement.Read)]
    public DataSet GetCityList(int provinceid)
    {
        string sql = "select * from city where father=" + provinceid;
        return GetDataSet(sql);
    }

    [Ajax.AjaxMethod(Ajax.HttpSessionStateRequirement.Read)]
    public DataSet GetAreaList(int cityid)
    {
        string sql = "select * from area where father=" + cityid;
        return GetDataSet(sql);
    }

    public static DataSet GetDataSet(string sql)
    {
        string ConnectionString =
            System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
        SqlDataAdapter sda = new SqlDataAdapter(sql, ConnectionString);
        DataSet ds = new DataSet();
        sda.Fill(ds);
        return ds;
    }
}

省列表在 Page_Load 中直接由伺服器端綁定(因為它是第一層,不需要 Ajax),並掛上 onclick 屬性觸發前端函式;市與區則完全交給 Ajax 動態載入。此外,GetProvinceList 沒有加 Ajax 標註,因為它只在頁面初次載入時由伺服器端呼叫。

web.config 設定

<httpHandlers>
  <add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax" />
</httpHandlers>

這段設定的作用是把 ajax/*.ashx 的請求全部導向 Ajax.NET 的 handler,前端那些看似直接呼叫後端方法的語法,實際上都是經由這個 handler 轉譯的。

實作提醒

範例中的 SQL 使用字串串接組出查詢條件,在正式環境請改用參數化查詢(SqlCommand.Parameters)以避免 SQL Injection。另外範例使用 document.all,這是 IE 專屬語法;若要跨瀏覽器,請改用 document.getElementById,並以 new Option(text, value) 搭配 add() 或 appendChild 來加入選項。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved