簡體   English   中英

對WCF JSON服務的jQuery ajax調用不起作用

[英]JQuery ajax call to WCF JSON service not working

我有一個簡單的WCF服務,該服務以JSON格式返回字符串列表。 WCF服務代碼如下所示:

Web.config

<system.serviceModel>
    <services>
        <service name="WcfServiceProto.Service1" 
                 behaviorConfiguration="ServiceBehavior1">
            <endpoint 
                address="" 
                behaviorConfiguration="EndPointBehavior"
                binding="webHttpBinding" 
                contract="WcfServiceProto.IService1" />
            <!--<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>-->
        </service>
    </services>
    <behaviors>
        <serviceBehaviors>
            <behavior name="ServiceBehavior1">
                <serviceMetadata httpGetEnabled="true"/>
                <serviceDebug includeExceptionDetailInFaults="true"/>
            </behavior>
        </serviceBehaviors>
        <endpointBehaviors>
            <behavior name="EndPointBehavior">
                <webHttp />
            </behavior>
        </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>

Service1.cs

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]     
public class Service1 : IService1
{
        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, 
                   BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        public List<string> AutoCompleteSearch(string query)
        {
            List<string> data = new List<string>(new string[] { "AB11", "AB12", "AB13", "BC11", "BC12", "BC13", "BC14", "CD11", "CD12", "CD13", "CD14", "CD15", "CD16", "CD17", "CD18", "CD19", "CD20", "CD21", "CD22", "CD23", "CD24", "CD25", "CD26", "CD27", "CD28", "CD29", "CD31", "CD32", "CD33", "CD34", "CD35", "CD36", "CD37", "CD38", "CD39", "CD41", "CD42", "CD43", "CD44", "CD45", "CD46", "CD47", "CD48", "CD49", "CD51", "CD52", "CD53", "CD54", "CD55", "CD56",});
            List<string> results = data.Where(item => item.ToUpper().StartsWith(query.ToUpper())).ToList();
            return results;
        }
    }

我正在嘗試使用JQuery ajax調用此服務,如下所示:

<script>    
    $(document).ready(function () {
        //alert("Hey");
        SearchText();
        function SearchText() {
            $("#Tags").autocomplete({
                source: function (request, response) {
                    alert($('#Tags').val());
                    $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "http://localhost:59227/Service1.svc/AutoCompleteSearch",
                        data: JSON.stringify({ query: $('#Tags').val() }),
                        dataType: "json",
                        dataFilter: function (data) { return data; },
                        success: function (data) {
                            alert("called");
                            response($.map(data, function (item) {
                                return { value: item };
                            }));
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(textStatus);
                        }
                    });
                }
            });
        }
    });
</script>

但是,當我在文本框中鍵入內容時,我沒有看到該列表。 我只看到帶有文本“錯誤”且沒有錯誤詳細信息的警報。 我還在WCF服務中插入了斷點,但它從未被擊中。 請讓我知道我在這兒做錯了什么。

瀏覽器控制台日志:

OPTIONS 
XHR 
http://localhost:59227/Service1.svc/AutoCompleteSearch


Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encodingg zip, deflate
Accept-Language en-US,en;q=0.5
Access-Control-Request-Headers content-type
Access-Control-Request-Method POST
Connection keep-alive
Host localhost:59227
Origin http://localhost:49910
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:48.0) Gecko/20100101 
Firefox/48.0

通過您的運營合同(接口IService1中的方法)提供WebInvoke屬性。 也可以嘗試設置UriTemplate屬性。 IMO,理想情況下,這應該是GET請求,而不是POST。

[WebInvoke(Method=“GET”, ResponseFormat=WebMessageFormat.Json, BodyStyle=WebMessageBodyStyle.Wrapped, UriTemplate=“AutoCompleteSearch?query={query}” )]

修改服務層后,更新$ .ajax以將GET用作type /使用$ .get()並將參數作為查詢字符串傳遞,名稱為“ query”。

function SearchText() {
        $("#Tags").autocomplete({
            source: function (request, response) {
                alert($('#Tags').val());
                var url = "http://localhost:59227/Service1.svc/AutoCompleteSearch?query="+$('#Tags').val();
                $.get(url)
                  .done(function(data){ // your success code goes here})
                  .fail(function(ex){ // you failure code goes here});
            }
        });
    }

我還沒有測試的$不用彷徨方法,看看這里如果你有任何問題- https://api.jquery.com/jquery.get/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM