2012-12-07 111 views
0

我正在學習WCF服務。我正試圖從Jquery調用RESTful服務。我的服務是如下使用JQuery Ajax調用WCF REST服務不起作用

服務類

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Runtime.Serialization; 
using System.ServiceModel; 
using System.Text; 
using System.ServiceModel.Activation; 

namespace RESTfulServiceLib 
{ 
[AspNetCompatibilityRequirements(RequirementsMode 
    = AspNetCompatibilityRequirementsMode.Allowed)] 
public class RestFullService : IRestFullService 
{ 
    public string Welcome(string Name) 
    { 
     return "Welcome to Restful Service " + Name; 
    } 
} 
} 

接口

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Runtime.Serialization; 
using System.ServiceModel; 
using System.ServiceModel.Web; 
using System.Text; 
using System.ServiceModel.Activation; 

namespace RESTfulServiceLib 
{ 

[ServiceContract] 

public interface IRestFullService 
{ 
    [OperationContract] 
    [WebInvoke(UriTemplate="/Welcome/{Name}",Method="GET",ResponseFormat=WebMessageFormat.Json)] 
    string Welcome(string Name); 
} 
} 

我創建了一個服務主機和SVC文件是這樣的

<%@ ServiceHost Language="C#" Debug="true" Service="RESTfulServiceLib.RestFullService" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %> 

我有以下配置設置

<configuration> 

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

<system.serviceModel> 
    <behaviors> 
     <endpointBehaviors> 
      <behavior name="EndPBhvr"> 
       <webHttp helpEnabled="true" defaultOutgoingResponseFormat="Json" 
        faultExceptionEnabled="true" /> 

      </behavior> 
     </endpointBehaviors> 
     <serviceBehaviors> 
      <behavior name="SvcBhvr"> 
       <serviceMetadata httpGetEnabled="true" /> 
      </behavior> 
     </serviceBehaviors> 
    </behaviors> 
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" /> 
    <services> 
     <service name="RESTfulServiceLib.RestFullService"> 
      <endpoint address="" behaviorConfiguration="EndPBhvr" 
       binding="webHttpBinding" bindingConfiguration="" name="EP1" 
       contract="RESTfulServiceLib.IRestFullService" /> 
     </service> 
    </services> 
</system.serviceModel> 
</configuration> 

運行的應用程序,當我瀏覽網址後的 「http://本地主機:2319/RESTFullService.svc /首頁/馬赫什」 它返回的值作爲

"Welcome to Restful Service Mahesh" 

我曾嘗試使用Jquery調用此服務。但我正在逐漸

error 200 undefined 

的腳本如下

<!DOCTYPE html> 
<html> 
<head> 
<script src="jquery-1.6.4.min.js"></script> 
<script > 
function ajaxcall() 
{ 
    $.ajax({ 
     url: "http://localhost:2319/RESTFullService.svc/welcome/mahesh", 
     type: "GET", 
     contentType: "application/json; charset=utf-8", 
     dataType:"jsonp", 
     data:{}, 
     processdata : true, 
     success: function(response) 
     { 
      var data= response.d; 
      alert(data); 
     }, 

     error: function(e) 
     { 
      alert('error '+e.status + ' ' + e.responseText); 
     } 
    }); 
} 
$().ready(function(){ 
    $('#btntest').click(ajaxcall); 
}) 
</script> 
</head> 
<body> 
<button id="btntest" >Click Me</button> 
</body> 
</html> 

什麼是錯誤的,我的編碼?請幫我...

感謝

馬赫什

+0

我已經加入「警戒工作(XMLHttpRequest.responseText) ;」和'alert(e.statusText)';'除了現在的錯誤部分,並嘗試。現在e.statusText顯示'成功'。這是什麼意思? –

回答

0

這是由於跨域問題。我做了一些配置文件的變化,它工作正常

更改後的配置文件。用crossDomainScriptAccessEnabled =「true」添加了新的綁定配置並添加到端點。並把aspNetCompatibilityEnabled =「false」

<configuration> 

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

<system.serviceModel> 
    <standardEndpoints /> 
    <bindings> 
     <webHttpBinding> 
      <binding name="Bind1" crossDomainScriptAccessEnabled="true" /> 
     </webHttpBinding> 
    </bindings> 
    <behaviors> 
     <endpointBehaviors> 
      <behavior name="EndPBhvr"> 
       <webHttp helpEnabled="true" defaultOutgoingResponseFormat="Json" 
        faultExceptionEnabled="true" /> 
      </behavior> 
     </endpointBehaviors> 
     <serviceBehaviors> 
      <behavior name="SvcBhvr"> 
       <serviceMetadata httpGetEnabled="false" /> 
      </behavior> 
     </serviceBehaviors> 
    </behaviors> 
     <serviceHostingEnvironment aspNetCompatibilityEnabled="false" /> 
    <services> 
     <service behaviorConfiguration="SvcBhvr" name="RESTfulServiceLib.RestFullService"> 
      <endpoint address="" behaviorConfiguration="EndPBhvr" binding="webHttpBinding" 
       bindingConfiguration="Bind1" name="EP1" contract="RESTfulServiceLib.IRestFullService" /> 
     </service> 
    </services> 
</system.serviceModel> 
</configuration> 

修改後的腳本,我添加了「?callback =?」在URL的結尾以JSON而不是JSONP獲取輸出。 JSONP將不給回調的URL

<!DOCTYPE html> 
<html> 
<head> 
<script src="jquery-1.6.4.min.js"></script> 
<script type="text/javascript" language="javascript"> 
    function ajaxcall() 
    { 
     $.ajax({ 
      url: "http://localhost:2319/RESTFullService.svc/welcome/mahesh?calback=?", 
      type: "GET", 
      dataType: "json", 
      contentType: "application/json; charset=utf-8", 
      data: {}, 
      processdata: true, 
      success: function (response) { 
       var data = response; 
       alert(data); 
      }, 

      error: function (e) { 
       alert('error ' + e.status + ' ' + e.responseText); 

      } 
      }); 
    } 

    $().ready(function(){ 
     $('#btntest').click(ajaxcall); 
    }) 
</script> 
</head> 
<body> 
    <button id="btntest" >Click Me</button> 
</body> 
</html> 

感謝我的同事Mrs.Poorani在CALSOFT實驗室幫助我解決這個問題

1

在你的jQuery的成功,你已經使用

// var data= response.d; 

,但你沒有返回一個有效的JSON。 您的回覆中沒有「d」。

+0

謝謝你的回覆。我在成功部分嘗試了'alert(「success」)''。但是我得到了同樣的錯誤。我認爲,由於其他錯誤,服務沒有成功 –

0
function CallService(sucessData) { 
$.ajax({ 
    // Add code for Cross Domain 
    headers: getHeaders(), 
    type: varType, //GET or POST or PUT or DELETE verb 
    url: varUrl, // Location of the service 
    data: varData, //Data sent to server 
    contentType: varContentType, // content type sent to server 
    dataType: varDataType, //Expected data format from server 
    processdata: varProcessData, //True or False 
    crossDomain: true, 
    cache: varCache, 
    timeout: 200000, 
    success: sucessData, 
    error: function (xhr) {// When Service call fails 
     fancyAlert("Error: " + xhr.responseText); 
     //fancyAlert('Error occured in Service Call'); 
    } 
}); 
}