2010-12-18 134 views
1

我創建了一個WCFREST.NET 4服務並將其部署到本地如果我使用Fiddler和使用要求的建設者,我能夠調用服務和看到數據已經返回OK。如果我嘗試在瀏覽器中碰到相同的REST位置,則JSON未返回,但看起來像XMLjQuery的Ajax調用從WCF RIA REST服務返回null

我的服務是這樣的:

[OperationContract] 
[WebGet(UriTemplate = "/{id}/details.json", 
    ResponseFormat=WebMessageFormat.Json)] 
public SampleItem Get(string id) 
{ 
    return new SampleItem{ Id=1, StringValue="value from string"}; 
} 

web.config文件只有輕微的變化:

<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" defaultOutgoingResponseFormat="Json"/> 

我想打電話給使用jQuery這樣的服務:

$(document).ready(function() { 
    $.ajax({ 
     type: "GET", 
     contentType: "application/json; charset=utf-8", 
     url: "http://wcf-rest/service1/1/details.json", 
     dataType: "json", 
     success: function (data) { alert(data); }, 
     error: function (e) { alert("error"); } 
    }); 
}); // end .ready 

但是,每次都返回null。我需要改變什麼?

回答

1

我一直在使用jQuery和Ajax廣泛使用JSON數據類型,我相信你需要將data更改爲data.d。看我下面的例子。

function getMakes() { 
    $.ajax({ 
     type: "POST", 
     url: "../../WebService_VehicleAssignment.asmx/getAllVehicleMakes", 
     data: "{}", 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     success: function (msg) { 
      var response = msg.d; 
      $('#output').empty(); 
      $.each(response, function (vehicle, vehicle) { 
       $('#output').append(new Option(vehicle.Make, vehicle.Id)); 
      }); 
     }, 
     failure: function (msg) { 
      alert('failure'); 
     } 
    }); 
}<br /> 

我用Firebug來調試這個東西。我可以確切地看到發佈到Web服務的內容以及返回的內容。如果網絡服務正在抱怨,那麼它在抱怨什麼。

瞭解爲什麼.d是必要的A breaking change between versions of ASP.NET AJAX。簡而言之,我認爲它是一個包裝,所以返回的數據被視爲一個字符串,而不是被返回並執行,如果它是原始文字JavaScript代碼。

+0

嗨,尼克,我試過你的建議,但msg.d爲空我厭倦了使用螢火蟲,但它並沒有真正告訴我很多。我想知道它是否與wcf rest服務沒有以瀏覽器請求的方式返回數據? – 2010-12-18 07:13:27

+0

@ user293545,你是否像我一樣設置了成功功能?在你的情況下,它會是alert(data.d);這是正確的語法,我希望我能幫助你更多。 – 2010-12-20 05:10:46