DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> JavaScript入門知識 >> AJAX入門 >> AJAX詳解
Ajax 實踐:文本框輸入即模糊查詢並填充下拉框
編輯:AJAX詳解     

本文實現這樣一個功能:用戶在文本框中輸入內容時,系統動態到數據庫中做模糊查詢,並把結果填充到下拉框中供選擇。這是一個非常實用的自動完成交互。

頁面與客戶端腳本

頁面由一個 TextBox1 和一個默認隱藏的下拉框 DropDownList1 組成。cityResult 函數取得文本框的值並調用後台 GetCityList;回調函數 get_city_Result_CallBack 在拿到結果後,先顯示下拉框、清空舊選項,再遍歷返回的 DataSet 逐項添加 Option:

function get_city_Result_CallBack(response) {
    if (response.value != null) {
        document.getElementById("DropDownList1").style.display = "block";
        document.getElementById("DropDownList1").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.getElementById("DropDownList1").options.add(new Option(name, id));
            }
        }
    } else {
        document.getElementById("DropDownList1").style.display = "none";
    }
}

此外 getData 函數在用戶點擊下拉框選項時,把選中項的文字回填到文本框,形成閉環。

後端服務

後端在 Page_Load 中通過 Ajax.Utility.RegisterTypeForAJax 註冊本頁類型,並為 TextBox1 綁定 onchange、為 DropDownList1 綁定 onclick。真正提供數據的方法用 [Ajax.AjaxMethod] 標記,根據關鍵字做模糊查詢:

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

需要特別提醒:示例中把用戶輸入直接拼進 like 語句,存在 SQL 注入風險,實際項目務必改用參數化查詢。配套的 city 表包含 id、cityID、city、father 等字段,以 father 維護行政區劃的父子關係。整體而言,這個方案讓用戶在鍵入時即可看到即時匹配的候選項,大幅提升了填寫效率。

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