0

使用 AJAX 实现 JQuery 自动完成

我很难使这个程序工作。我想要做的是使用 JQuery UI API 实现自动完成并从启用 AJAX 的 WCF 服务中获取结果。

我相信我的问题是到达 Web 服务(如果我将它实现为 asmx 而不是 svc 它似乎正在工作)

默认.aspx

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="SandwichServices._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    <script src="Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery-ui-1.8.21.custom.min.js" type="text/javascript"></script>
    <link href="Styles/jquery-ui-1.8.21.custom.css" rel="stylesheet" type="text/css" />
    <script language="javascript" type="text/javascript">
// <![CDATA[
        $(document).ready(function () {
            $(".searchinput").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "~/CostService.svc/GetAllPredictions",
                        data: "{'keywordStartsWith':'" + request.term + "'}",
                        dataType: "json",
                        async: true,
                        success: function (data) {
                            response(data.d);
                        },
                        error: function (result) {
                            alert("Due to unexpected errors we were unable to load data");
                        }
                    });
                },
                minLength: 2
            });
        });

// ]]>
    </script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
        <Services>
            <asp:ServiceReference Path="CostService.svc" />
        </Services>
    </asp:ScriptManager>
    <div class="ui-widget">
        <asp:Label ID="lblSearch" Text="Search" AssociatedControlID="txbSearchKeyword" runat="server"></asp:Label>
        <asp:TextBox ID="txbSearchKeyword" runat="server" CssClass="searchinput"></asp:TextBox>
        <asp:Button ID="Button2" Text="Go!" runat="server" OnClick="Search_Click" />
    </div>
    <asp:Literal ID="litStatus" runat="server"></asp:Literal>
</asp:Content>

默认.aspx.cs

using System;

namespace SandwichServices
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Search_Click(object sender, EventArgs e)
        {
            litStatus.Text = "Search conducted for keyword: " + txbSearchKeyword.Text;
        }
    }
}

成本服务.svc.cs

using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Activation;

namespace SandwichServices
{
    [ServiceContract(Namespace = "SandwichServices")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class CostService
    {
        private readonly List<string> _names = new List<string> // dummy list
                                         {
                                             "one",
                                             "one111",
                                             "one2222",
                                             "one4444",
                                         };

        [OperationContract]
        public IList<string> GetAllPredictions(string keywordStartsWith)
        {
            IList<string> output = (from c in _names
                                    where c.Contains(keywordStartsWith)
                                    select c).ToList();
            return output;
        }
    }
}

网络配置:

<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
  <connectionStrings>
    <add name="ApplicationServices"
         connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
         providerName="System.Data.SqlClient" />
  </connectionStrings>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />

    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login.aspx" timeout="2880" />
    </authentication>

    <membership>
      <providers>
        <clear/>
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
             enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
             maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
             applicationName="/" />
      </providers>
    </membership>

    <profile>
      <providers>
        <clear/>
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
      </providers>
    </profile>

    <roleManager enabled="false">
      <providers>
        <clear/>
        <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
        <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
      </providers>
    </roleManager>

  </system.web>

  <system.webServer>
     <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="SandwichServices.CostServiceAspNetAjaxBehavior">
          <enableWebScript />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
      multipleSiteBindingsEnabled="true" />
    <services>
      <service name="SandwichServices.CostService">
        <endpoint address="" behaviorConfiguration="SandwichServices.CostServiceAspNetAjaxBehavior"
          binding="webHttpBinding" contract="SandwichServices.CostService" />
      </service>
    </services>
  </system.serviceModel>
</configuration>

编辑: 控制台说:

发布 http://XXXXXX:7070/~/CostService.svc/GetAllPredictions 404(未找到)”

我怎样才能达到它?

4

1 回答 1

1

让它变得 RESTful!

但首先将您的服务拆分为合同(接口)和实现(类)。

然后将此添加到您的 GetAllPredictions-Method

[WebInvoke(Method = "POST", 
                    ResponseFormat = WebMessageFormat.Json, 
                    UriTemplate = "predictions/{keywordStartsWith}")]

这使它成为 RESTful

添加webHttpenpointPoint-Behaviour。

<behavior name="SandwichServices.CostServiceAspNetAjaxBehavior">
    <webHttp />
    <enableWebScript />
</behavior>

然后尝试调用它:

$(document).ready(function () {
        $(".searchinput").autocomplete({
            source: function (request, response) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "/predictions/" + request.term,
                    async: true,
                    success: function (data) {
                        response(data.d);
                    },
                    error: function (result) {
                        alert("Due to unexpected errors we were unable to load data");
                    }
                });
            },
            minLength: 2
        });
    });

您可能需要删除以下行:

    <Services>
        <asp:ServiceReference Path="CostService.svc" />
    </Services>
于 2012-07-06T14:28:25.600 回答