开发者

jQuery Ajax call returning null from WCF RIA REST service

开发者 https://www.devze.com 2023-01-31 00:44 出处:网络
I have created a WCF REST .NET 4 service and deployed it to a local IIS 7. If I use Fiddler and use the request builder, I am able to call the service and see the data been returned OK. If I try hitti

I have created a WCF REST .NET 4 service and deployed it to a local IIS 7. If I use Fiddler and use the request builder, I am able to call the service and see the data been returned OK. If I try hitting the same REST location in the browser, JSON is not been returned but it looks like XML.

My service looks like this:

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

My web.config file has only a slight change:

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

I am trying to call the service using jQuery like this:

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

However, null is being returned every time. What do I need to change?


I've been using jQuery and Ajax extensively with a JSON datatype, and I believe you need to change data to data.d. See my example below.

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

I use Firebug to debug this stuff. I can see exactly what's getting posted to the web service and what is coming back. And if the web service is complaining, what it's complaining about.

Read about why the .d is necessary in A breaking change between versions of ASP.NET AJAX. In short, I believe it is a wrapper so that returned data is treated as a string rather than being returned and executed if it is raw literal JavaScript code.

0

精彩评论

暂无评论...
验证码 换一张
取 消