2012-08-02 2 views
1

위의 내용이 모두 만족 스럽습니다. 서비스가 제대로 작동하는지 3 가지로 알려주 었습니다. 자바 스크립트AutoComplete Not firing

<script language="javascript"> 


$(function() { 
    $("#postcode").autocomplete({ 
     source: "AutoCompleteService.asmx/FindAddresses", 
     minLength: 1, 
     select: function (event, ui) { 
      $(this).val(ui.item.value); 
     } 
    }); 
}); 
</script> 

얹는

/// <summary> 
/// Summary description for AutoCompleteService 
/// </summary> 
[WebService(Namespace = "http://schemas")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
[System.ComponentModel.ToolboxItem(false)] 
[System.Web.Script.Services.ScriptService] 
public class AutoCompleteService : BaseWebService 
{ 
    /// <summary> 
    /// Gets or sets the account finder service. 
    /// </summary> 
    public ICheckoutService CheckOutService { get; set; } 

    /// <summary> 
    /// Finds all addresses matching either the postcode or suburb given in the prefix text. 
    /// </summary> 
    /// <param name="prefixText">The prefix text.</param> 
    /// <param name="count">The count.</param> 
    /// <returns>Aray of address details</returns> 
    [WebMethod] 
    public string[] FindAddresses(string prefixText, int count) 
    { 
     //Check the parameters 
     if (count == 0) count = 10; 
     var suburbs = CheckOutService.FindMatchingForPartialAddress(prefixText); 
     return suburbs.Take(count).ToArray(); 


    } 
} 

텍스트 상자에 얹는

 <asp:TextBox runat="server" name="postcode" id="postcode" ></asp:TextBox> 

응답

<ArrayOfStringxmlns: xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns: xsd="http://www.w3.org/2001/XMLSchema"xmlns="http://schemas.forcetechnology.com.au/2009/04/Fulfilment"><string>ABBARIVER,WA,6280</string><string>ABBEY,WA,6280</string><string>ACTONPARK,WA,6280</string>string>ADAMSVALE,WA,6375</string></ArrayOfString> 

좋아, 내가 만든 다음 변경 올바른 direc 나를 가리키는 대한 감사합니다 모두 그리고 나에게 출발점을 제공하고, 또한이 메시지는 나에게 도움이되는 오류 메시지를 제공하므로 수정 된 것이 아래에있다.

  [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public string[] FindAddresses(string prefixText) 
    { 
     //Check the parameters 

     var suburbs = CheckOutService.FindMatchingForPartialAddress(prefixText); 
     return suburbs.ToArray(); 


    } 


    $(document).ready(function() { 
    $('[ID$=postcode]').live('keyup.autocomplete', function() { 

     $(this).autocomplete({ 
      source: function (request, response) { 
       alert(request.term); 
       $.ajax({ 
        url: '<%=ResolveUrl("AutoCompleteService.asmx/FindAddresses") %>', 
        data: "{ prefixText:'" + request.term + "'}", 
        dataType: "json", 
        type: "POST", 
        contentType: "application/json; charset=utf-8", 
        success: function (data) { 
         response($.map(data.d, function (item) { 
          return { 
           label: item.split('-')[0], 
           val: item.split('-')[1] 
          } 
         })) 
        }, 
        error: function (response) { 
         alert(response.responseText); 
        }, 
        failure: function (response) { 
         alert(response.responseText); 
        } 
       }); 
      }, 
      select: function (e, i) { 
      }, 
      minLength: 1 
     }); 
    }); 
}); 
+0

당신이 오류를받을 수 있나요이다 .. 나를 위해 노력하고 있습니다? –

+0

텍스트 상자 요소의 실제 ID가 다를 수 있으므로 jQuery는 텍스트 요소를 찾지 못합니다. 마크 업에'ClientIDMode = "Static"을 추가하십시오. –

+0

@ ShadowWizard 제공 OP가 .net 4를 사용하고 있습니다. – Flash

답변

1

다음 코드를 시도 가지고 있는지 확인 할 수있다. 그

$(document).ready(function() { 
     $('[ID$=txtLastname]').live('keyup.autocomplete', function() { 

      $(this).autocomplete({ 
       source: function (request, response) { 
        $.ajax({ 
         url: '<%=ResolveUrl("~/Resources/WebService.asmx/LastName") %>', 
         data: "{ 'prefix': '" + request.term + "'}", 
         dataType: "json", 
         type: "POST", 
         contentType: "application/json; charset=utf-8", 
         success: function (data) { 
          response($.map(data.d, function (item) { 
           return { 
            label: item.split('-')[0], 
            val: item.split('-')[1] 
           } 
          })) 
         }, 
         error: function (response) { 
          alert(response.responseText); 
         }, 
         failure: function (response) { 
          alert(response.responseText); 
         } 
        }); 
       }, 
       select: function (e, i) { 
       }, 
       minLength: 1 
      }); 
     }); 

웹 방법은

[WebMethod] 
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
public string[] LastName(string prefix) 
{ 
    List<string> customers = new List<string>(); 
    using (SqlConnection conn = new SqlConnection()) 
    { 
     string connectionstring = CCMMUtility.GetCacheForWholeApplication(); 
     conn.ConnectionString = connectionstring; 
     using (SqlCommand cmd = new SqlCommand()) 
     { 
      cmd.CommandText = "select distinct top(10) Lastname from tblusers where " + 
      "Lastname like '%'+ @SearchText + '%' order by Lastname"; 
      cmd.Parameters.AddWithValue("@SearchText", prefix); 
      cmd.Connection = conn; 
      conn.Open(); 
      using (SqlDataReader sdr = cmd.ExecuteReader()) 
      { 
       while (sdr.Read()) 
       { 
        customers.Add(string.Format("{0}", sdr["Lastname"])); 
       } 
      } 
      conn.Close(); 
     } 
     return customers.ToArray(); 
    } 
} 
2

자동 완성이 JQueryUI이며 다음 소스를 설정하는 기능을 제공해야합니다 자동 완성에 일부 사용자 지정 매개 변수를 제공하는 경우. Have a look here 이렇게하면 정의하는 데 도움이됩니다.

또한 @으로 그림자 - 챔피온은 당신이 올바른 ID의

+0

죄송합니다 자동 완성에 대한 기본 매개 변수가 "t"인 이유를 잊어 버렸습니다. 그래서 t 소스로 함수를 제공해야합니다. – Qpirate