問題描述:當咱們在textbox中輸入字的時候,但願相關字下拉提示,供選擇。javascript
解決辦法:使用jquery實現。css
一、在.net中建立文件:Handler.ashx,代碼以下:html
<%@ WebHandler Language="C#" class="Handler" %>java
using System; using System.Web;// 添加兩個命名空間 using System.Collections.Generic; using System.Web.Script.Serialization; using System.Data; using System.Data.SqlClient; namespace ZQY.Report.CollectInfo { /// <summary> /// Handler 的摘要說明 /// </summary> public class Handler : IHttpHandler { /// <summary> /// 根據關鍵字過濾內容 /// /// </summary> /// <param name="keyword">關鍵字</param> /// /// <returns>過濾數組</returns> private string[] GetFilteredList(string keyword) { List<string> countryList = new List<string>(); //此處選項通常從數據庫中讀取,而後循環添加給countrylist對象便可。 DataSet ds = new DataSet();//建立數據集; SqlConnection conn = new SqlConnection(DBHelper.ConnectionString); try { string sql = " SELECT distinct [company_name] FROM [dbo].[dim_company]"; SqlDataAdapter dr = new SqlDataAdapter(sql, conn);//上面兩句能夠合併成這一 dr.Fill(ds); //填充數據集 for (int i = 0; i < ds.Tables[0].Rows.Count;i++ ) { countryList.Add(ds.Tables[0].Rows[i]["company_name"].ToString()); } } catch (Exception ex) { //conn.Close(); 關閉數據庫鏈接 if (conn.State == ConnectionState.Open) //判斷數據庫鏈接狀態,是否鏈接 { conn.Close(); } } //conn.Close(); 關閉數據庫鏈接 if (conn.State == ConnectionState.Open) //判斷數據庫鏈接狀態,是否鏈接 { conn.Close(); } List<string> filteredList = new List<string>(); foreach (string sCountry in countryList) { // 判斷是否包含關鍵字的國家,而後加入到過濾後的集合中。 if (sCountry.Contains(keyword)) { filteredList.Add(sCountry); } } // 返回數組,以便後面能序列化爲JSON格式數據 return filteredList.ToArray(); } public void ProcessRequest(HttpContext context) { string keyword = context.Request.QueryString["keyword"]; if (keyword != null) { JavaScriptSerializer serializer = new JavaScriptSerializer(); // 經過JavaScriptSerializer對象的Serialize序列化爲["value1","value2",...]的字符串 string jsonString = serializer.Serialize(GetFilteredList(keyword)); context.Response.Write(jsonString); // 返回客戶端json格式數據 } } public bool IsReusable { get { return false; } } } }
二、建立Default.aspx文件:代碼以下:jquery
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>無標題頁</title> <link type="text/css" rel="Stylesheet" href="js/jquery-ui-1.8.16.custom.css" /> <script type="text/javascript" src="js/jquery-1.6.2.min.js"></script> <script type="text/javascript" src="js/jquery-ui-1.8.16.custom.min.js"></script> <%-- 此處爲juery調用腳本--%> <script type="text/javascript"> $(function () { $("#txtSearch").autocomplete({ minLength: 1, // 設置搜索的關鍵字最小長度// 設置自動完成列表的函數,函數包括兩個參數,requset和response source: function (request, response) { $.ajax({ type: "POST", // 經過request.term能夠得到文本框內容 url: "Handler.ashx?keyword=" + request.term, contentType: "application/json; charset=gb2312", dataType: "json", success: function (data) { // jQuery.map(array, callback) :將一個數組中的元素轉換到另外一個數組中。 // 下面就是把數組["value1", "value2",...]轉換爲[{value:"value1"}, {value:"value2"},...] response($.map(data, function (item) { return { value: item }; })); }, error: function () { alert("ajax請求失敗"); } }); } }); }); </script> </head> <body> <form id="form1" runat="server"> <div align="center"> <fieldset style="width: 400px; height: 100px;"> <table border="0" cellpadding="3" cellspacing="3"> <tr> <td> <asp:Label ID="lblCountry" runat="server">國家:</asp:Label> </td> <td> <asp:TextBox ID="txtSearch" runat="server" Width="150px"></asp:TextBox> </td> </tr> </table> </fieldset> </div> </form> </body> </html>
三、實現效果如上圖所示:ajax
總結:使用jquery時,需首先下載以下包:jquery-ui-1.8.16.custom.zip(下載地址:http://jqueryui.com/download)sql
內部包含以下三個文件:jquery-ui-1.8.16.custom.css jquery-1.6.2.min.js jquery-ui-1.8.16.custom.min.js數據庫
若是是漢字:須要在配置文件中加入以下: <globalization requestEncoding="gb2312" responseEncoding="gb2312" />json
不然可能產生亂碼!數組