Jquery:ajax 调用正常工作且自动完成功能不适用于 WCF

发布于 2024-10-03 01:24:42 字数 4909 浏览 2 评论 0原文

我正在使用 jquery 来了解如何使用自动完成

我有两个输入类型文本 exampleexample2。 我只是想知道为什么它适用于 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/");
});

这是 fiddler 中对 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

这是 fiddler 中失败时 autocomplete 的结果:

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>

I'm using jquery to figure out how to use autocomplete.

I have two input type text example, and example2.
I just would like to know why it works for ajax call for example textbox and not for autocomplete method on example2 textbox.

Here is the WCF service interface:

[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);
}

When I use ajax call it works nicely:

$(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/");
});

Here is the request for autocomplete in fiddler:

GET http://localhost.:62138/MyService.svc/GetCompletions/?q=apri&limit=150×tamp=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

Here is the result for autocomplete when fails in 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>

Here is the 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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

送舟行 2024-10-10 01:24:42

现在我得到了这个 example2 文本框,可以自动完成工作。
我修复了以下一些内容:

在 javascript 中,删除尾部斜杠 (/):web.config

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

,替换为一个没有奇怪的周数的新斜杠:

<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());
        }
    }

Now I got this example2 textbox with autocomplete working.
Here somethings I've fixed:

in javascript, remove trailing slash(/):

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

web.config, replaced by a new one without wierd tweeks:

<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>

interface:

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

a very important tweek in class method GetCompletions to obey autocomplete plugin expected format:

[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());
        }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文