Jquery: вызов ajax работает и автозаполнение не работает с WCF - PullRequest
0 голосов
/ 13 ноября 2010

Я использую jquery, чтобы понять, как использовать autocomplete.

У меня есть два типа ввода текста example и example2. Я просто хотел бы знать, почему он работает для вызова ajax, например, текстовое поле, а не для метода автозаполнения в текстовом поле example2.

Вот интерфейс службы WCF:

[ServiceContract]
public interface IMyService
{
    [WebInvoke(Method = "GET",
           RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json,
           UriTemplate = "getcompletions/q={q}&limit={limit}")]
    List<String> GetCompletions(string q, string limit);
}

Когда я использую вызов ajax, он прекрасно работает:

$(document).ready(function () {
   var url = "http://localhost.:62138/";
   var data = null;
   /*
   //this webservice call works for UriTemplate = "getcompletions/{q}"
   $.ajax({
       url: url + "MyService.svc/GetCompletions/" + $('#example').val(),
       cache: false,
       type: "GET", // http method
       dataType: "json",
       error: function (XMLHttpRequest, status, error) {
            //alert("Error p1 s(" + status + ") e(" + error + ")");
       },
       success: function (msg, arg2, xhr) {
            try {
                if (msg !== null) {data = msg;}
                else { alert("msg is null"); }
            } catch (e) { alert("exception: " + e); }}
    }); 
    */
    //but this doesn't work
    $('#example2').autocomplete(url + "MyService.svc/GetCompletions/");
});

Вот запрос для autocomplete в фиддлере:

GET http://localhost.:62138/MyService.svc/GetCompletions/?q=apri&limit=150&timestamp=1289668676175 HTTP/1.1
Accept: */*
Accept-Language: en-US
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; .NET4.0E; .NET4.0C)
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
Host: localhost.:62138

Вот результат для autocomplete при сбое в fiddler:

HTTP/1.1 404 Not Found
Server: ASP.NET Development Server/10.0.0.0
Date: Sat, 13 Nov 2010 17:19:53 GMT
X-AspNet-Version: 4.0.30319
Content-Length: 1565
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Connection: Close

<?xml version="1.0" encoding="utf-8"?>
<!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>
    <title>Service</title>
    <style>blabla....</style>
  </head>
  <body>
    <div id="content">
      <p class="heading1">Service</p>
      <p>Endpoint not found.</p>
    </div>
  </body>
</html>

Вот web.config

<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <add name="MyConnectionString" connectionString="Data Source=(local);Initial Catalog=BRAZIL;Integrated Security=True;" providerName="System.Data.SqlClient"/>
  </connectionStrings>
    <system.web>
        <compilation debug="true" targetFramework="4.0"/>
    </system.web>
    <system.serviceModel>
        <services>
            <service name="YourCompany.Services.MyService" 
               behaviorConfiguration="anotherBehavior">
                <endpoint address="" 
                  behaviorConfiguration="endPointBehavior" 
                  binding="webHttpBinding" 
                  contract="YourCompany.Services.IMyService"/>

        <endpoint address="mex"
                  binding="mexHttpBinding"
                  contract="IMetadataExchange" />
            </service>
        </services>
        <behaviors>
            <endpointBehaviors>
                <behavior name="endPointBehavior">
          <!--post <enableWebScript/>-->
          <webHttp />
                </behavior>

      </endpointBehaviors>
            <serviceBehaviors>
                <behavior name="anotherBehavior">
                    <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
                    <serviceMetadata httpGetEnabled="true"/>
                    <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
                    <serviceDebug includeExceptionDetailInFaults="true"/>
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true"/>
    </system.serviceModel>
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
    </system.webServer>
</configuration>

1 Ответ

0 голосов
/ 14 ноября 2010

Теперь я получил это текстовое поле example2 с автозаполнением.Вот что я исправил:

в javascript, удалите косую черту (/):

$('#example2').autocomplete(url + "ChatService.svc/GetCompletions");

web.config, заменен новым без странных твиков:

<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="myBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="myBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service behaviorConfiguration="myBehavior" name="YourCompany.Services.MyService">
        <endpoint address="" binding="webHttpBinding" contract="YourCompany.Services.IMyService" behaviorConfiguration="myBehavior"/>
      </service>
    </services>
  </system.serviceModel>

интерфейс:

[ServiceContract(Namespace = "YourCompany.Services")]
    public interface IMyService
    {
        [OperationContract]
        [WebInvoke(Method = "GET", UriTemplate = "GetCompletions?q={q}", ResponseFormat = WebMessageFormat.Json)]
        string GetCompletions(string q);
    }

очень важный трюк в методе класса GetCompletions для выполнения ожидаемого формата автозаполнения плагина:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class MyService : IMyService
    {

        public string GetCompletions(string q)
        {
            List<String> words = new List<String> {
                  "January", "February", "March", "April", "May", "June",
                  "July", "August", "September", "October", "November",
                  "December", "Yammer", "Yaw", "Yawn", "Auspiscious",
                  "Arbitrage", "Arbiter", "Arbor", "Ardor", "Ardent",
                  "Concrete", "Conscious", "Uptight", "Uplevel", "Friend",
                  "Depend", "Deepend", "Deepen", "Decommit", "Right", "Now",
                  "Knowledge", "Knight", "Know", "Knickers", "Wow", "Holy",};

            var selection = from candidate in words
                            where candidate.ToUpper().StartsWith(q.ToUpper())
                            select candidate;

            //autocomplete funny format
            return string.Join("\n", selection.ToArray());
        }
    }
...