使用jQuery與WebService 實現AutoComplete For jquery-1.3.2.js

使用jQuery與WebService 實現AutoComplete For jquery-1.3.2.js

一.如想要使用【官方jquery.autocomplete.js】來實作 【Sever control】 則必須修改 【官方jquery.autocomplete.js】內容.

【官方jquery.autocomplete.js】修改地方如下共有4處:

1/4: 新增代碼

 

$.fn.extend({  // .extend : 物件延展及簡單繼承
	autocomplete: function(urlOrData, options) {
	    var isUrl = typeof urlOrData == "string"; /* 在此行下加入下面代碼 */
	    
        /* ↓ ☆☆☆☆ 追加段落 ☆☆☆☆ ◎ For 新增如以物件輸入時 0226'09  */    
	    var isObj= typeof(urlOrData.Method) =="string" ;
		if (isObj== true){    //
 		  options = $.extend({},urlOrData);
          urlOrData=options.URL;	
          isUrl = true;	 
		}
		/* ↑ ☆☆☆☆ 追加段落 ☆☆☆☆ ◎ For 新增如以物件輸入時 0226'09  */   	    

2/4:新增代碼

 

	}).bind("unautocomplete", function() {
		select.unbind();
		$input.unbind();
		$(input.form).unbind(".autocomplete");  /* 在此行下加入下面代碼 */

	/* ↓ ☆☆☆☆ 追加段落 ☆☆☆☆ ◎ For 使用輸入法時 0226'09  */
	}).bind("input", function() {        
		onChange(0, true);               
	/* ↑ ☆☆☆☆ 追加段落 ☆☆☆☆ ◎ For 使用輸入法時 0226'09  */
	});

3/4:找到 $.ajax() 進行修改

 

      /* ↓ ☆☆☆☆ 修改段落 ☆☆☆☆ ◎ For WebService 0226'09  */
		    $.ajax({
                dataType:'xml',
                     url: options.url + "/" + options.Method,                            /* Web服務器URL , 服務器的副程式 */
                    type:'post',
                 // data: {prefixText:input.value,count:'jq',contextKey:'jq測試中...' }, /* For jquery-1.2.6.js 版本 */
                 /* jquery-1.3.2.js 版本 data傳輸改以字串傳輸  */
                    data: "prefixText=" + input.value + "&count=" + options.Count + "&contextKey=" + options.Contextkey  ,  //For jquery-1.3.2.js 版本
                 success: function(oXml) {
                   var xmlDoc=oXml.childNodes(1).firstChild.nodeValue;
                   var pars = eval ("(" + xmlDoc + ")");                                 /* 用戶端 JSON 反序列化還原物件 */
                   var parsed = options.pars && options.parse(pars) || parse(pars);
                   cache.add(term, parsed);
			       success(term, parsed);
                 }
            })
      /* ↑ ☆☆☆☆ 追加段落 ☆☆☆☆ ◎ For WebService 0226'09  */      

4/4: 找到 function parse(data) 進行修改

 

	function parse(data) { 
		var parsed = [];
		
    /* ↓ ☆☆☆☆ 修改段落 ☆☆☆☆ ◎ For WebService 0226'09  */		
	/*	var rows = data.split("\n");   以"\"做為陣列切割符號 */
	    var rows = data  // 替代上面那一行
	/* ↑ ☆☆☆☆ 追加段落 ☆☆☆☆ ◎ For WebService 0226'09  */      
	
		for (var i=0; i < rows.length; i++) {
			var row = $.trim(rows[i]);
			if (row) {
				row = row.split("|");
				parsed[parsed.length] = {
					data: row,
					value: row[0],
					result: options.formatResult && options.formatResult(row, row[0]) || row[0]
				};
			}
		}
		return parsed;
	};

二.實作 【Sever control】:搭配 WebService 使用.

Namespace WebControls
    ''' <summary>
    ''' 自動輸入控制項。
    ''' </summary>
    <Description("自動輸入控制項。"), _
     Designer(GetType(TBTextBoxAutoCompleteDesigner)), _
    ToolboxData("<{0}:TBTextBoxAutoComplete runat=server></{0}:TBTextBoxAutoComplete>")> _
    Public Class TBTextBoxAutoComplete
        Inherits System.Web.UI.WebControls.CompositeControl
        Private FControlID As String = String.Empty
        Private FServiceURL As String = String.Empty
        Private FServiceMethod As String = String.Empty
        Private FContextKey As String = String.Empty
        Private FCount As Integer = 0
        Private FUser_Serch_Table_Coun As String = String.Empty
        Private FUser_File_Table As String = String.Empty
        Private FUser_File_Patch As String = String.Empty

        Structure Sever_Data
            Dim URL As String
            Dim Method As String
            Dim Count As Integer
            Dim Contextkey As String
        End Structure

#Region " 屬性 "
        ''' <summary>
        ''' 作用的控制項 ID。
        ''' </summary>
        <NotifyParentProperty(True), Description("選擇自動輸入TextBox ID。"), TypeConverter(GetType(AssociatedControlConverter)), DefaultValue("")> _
       Public Property User_ControlID() As String
            Get
                Return FControlID
            End Get
            Set(ByVal value As String)
                FControlID = value
            End Set
        End Property

        ''' <summary>
        ''' 輸入 Web 服務。(*.asmx)。
        ''' </summary>
        <NotifyParentProperty(True), Description("Web 服務的位置。(*.asmx)"), Editor(GetType(UrlEditor), GetType(UITypeEditor)), DefaultValue("")> _
       Public Property User_ServiceURL() As String
            Get
                Return FServiceURL.Replace("~/", "")
            End Get
            Set(ByVal value As String)
                FServiceURL = value
            End Set
        End Property

        ''' <summary>
        ''' Web 服務的 WebMethod 副程式。
        ''' </summary>
        <NotifyParentProperty(True), Description("Web 服務的 WebMethod 副程式。"), DefaultValue("")> _
       Public Property User_ServiceMethod() As String
            Get
                Return FServiceMethod
            End Get
            Set(ByVal value As String)
                FServiceMethod = value
            End Set
        End Property

        ''' <summary>
        ''' 設定伺伏器所需參數。
        ''' </summary>
        <NotifyParentProperty(True), Description("設定伺伏器所需參數。"), DefaultValue("")> _
       Public Property User_ContextKey() As String
            Get
                Return FContextKey
            End Get
            Set(ByVal value As String)
                FContextKey = value
            End Set
        End Property

        ''' <summary>
        ''' Count 參數。
        ''' </summary>
        <NotifyParentProperty(True), Description("設定下拉筆數。" & Chr(10) & "最大50筆。"), DefaultValue("")> _
       Public Property User_Count() As Integer
            Get
                If FCount > 50 Then FCount = 50
                Return FCount
            End Get
            Set(ByVal value As Integer)
                FCount = value
            End Set
        End Property

        ''' <summary>
        ''' 欲連結資料檔的位置。
        ''' </summary>
        <NotifyParentProperty(True), Description("欲連結資料檔的位置。"), Editor(GetType(UrlEditor), GetType(UITypeEditor)), DefaultValue("")> _
       Public Property User_File_Patch() As String
            Get
                Return FUser_File_Patch.Replace("~/", "")
            End Get
            Set(ByVal value As String)
                FUser_File_Patch = value
            End Set
        End Property

        ''' <summary>
        ''' 欲連結資料檔的表單名 。
        ''' </summary>
        <NotifyParentProperty(True), Description("欲連結資料檔的表單名。" & Chr(10) & "檔案類型【Excel】請加上 $。"), DefaultValue("")> _
       Public Property User_File_Table() As String
            Get
                Return FUser_File_Table
            End Get
            Set(ByVal value As String)
                FUser_File_Table = value
            End Set
        End Property

        ''' <summary>
        ''' 欲比對標題欄的欄名。
        ''' </summary>
        <NotifyParentProperty(True), Description("欲比對標題欄的欄名。"), DefaultValue("")> _
       Public Property User_Serch_Table_Coun() As String
            Get
                Return FUser_Serch_Table_Coun
            End Get
            Set(ByVal value As String)
                FUser_Serch_Table_Coun = value
            End Set
        End Property
#End Region


        ''' <summary>   
        ''' 覆寫 OnLoad 方法。   
        ''' </summary>   
        Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
            Dim Include_Regis_Url As String
            '註冊 CSS , 檔案:jquery.autocomplete.css
            Include_Regis_Url = Page.ClientScript.GetWebResourceUrl(Me.GetType(), "TakasiControls.jquery.autocomplete.css")
            Takasi_Web_Lib.Include_Regis_Css_Js(Me.Page, "jquery.autocomplete.css", Include_Regis_Url, "CSS")
            '註冊 Javascript , 檔案:jquery.autocomplete.js
            Include_Regis_Url = Page.ClientScript.GetWebResourceUrl(Me.GetType(), "TakasiControls.jquery.autocomplete.js")
            Takasi_Web_Lib.Include_Regis_Css_Js(Me.Page, "jquery.autocomplete.js", Include_Regis_Url, "js")
            MyBase.OnLoad(e)
        End Sub


        ''' <summary>   
        ''' 覆寫 Render 方法。   
        ''' </summary>   
        Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
            Dim oScript As StringBuilder
            Dim sScript As String
            Dim sJson As String = String.Empty
            Dim Write_Data As Sever_Data
            Write_Data.URL = FServiceURL
            Write_Data.Method = FServiceMethod
            Write_Data.Count = FCount
            If FContextKey <> "" Then
                FContextKey = "," & FContextKey
            End If
            Dim o_p As String = User_File_Patch
            Dim Point As Integer = o_p.LastIndexOf("/")
            Dim patch As String = String.Empty
            Dim file As String = String.Empty
            If Point >= 0 Then
                patch = o_p.Substring(0, Point + 1)
                file = o_p.Substring(Point + 1)
                file = file.Remove(file.LastIndexOf("."))
            End If
            Write_Data.Contextkey = "Patch:" & patch & "," & _
                                    "File:" & file & "," & _
                                    "Table:" & User_File_Table & "," & _
                                    "Table_Coun:" & User_Serch_Table_Coun & FContextKey
            sJson = TakasiControls.WebFunc.JsonSerialize(Write_Data)   '伺服端 JSON 序列化
            oScript = New StringBuilder()
            oScript.AppendLine("$(function() {")
            oScript.AppendLine("  $('#" & FControlID & "').autocomplete(" & sJson & ");")
            oScript.AppendLine("}); ")
            sScript = oScript.ToString
            Me.Page.ClientScript.RegisterStartupScript(Me.GetType(), Me.ClientID, sScript, True)
            MyBase.Render(writer)
        End Sub

          End Class
End Namespace

 

大致上是如此.....其實我也是不知清楚如何修改,呵...^.^|||

如代碼部份有問題,請高手指點一二吧...