views:

42

answers:

1

Hi

I am having this exact problem as raised in this question

http://stackoverflow.com/questions/1121559/asp-net-json-web-service-always-return-the-json-response-wrapped-in-xml

It's late and I have been sitting in this chair for 10 hours now trying to get ajax and json to work and all I got was deeply frustrated.

So does anyone know how to make my webservice not return my json object wrapped in xml? If I just do a straight dataType: "json" then I get nothing. I have to do dataType: "jsonp" to get anything back from the server at all. But once I do jsonp I get my json wrapped in xml.

Please help Thanks Cheryl

+2  A: 

If you set the response type to json jQuery is then checking the response to see if it's valid JSON (and since it's XML, that's not the case)...when it's not valid, it silently fails since jQuery 1.4+.

There are 3 important bits when making your request, by default it needs to be a POST and you need to set the contentType to "application/json; charset=utf-8" like this:

$.ajax({
  url: 'MyService.asmx/Method',
  type: 'POST',
  data: myData,
  dataType: 'json',
  contentType: "application/json; charset=utf-8",
  success: function(data) {
    //do something with data
  }
});

Then on the server-side make sure you have the ScriptService attribute set, here's an example very minimal layout:

[WebService] //here by default when you create the service
[ScriptService]
public class MyService : System.Web.Services.WebService 
{
  [WebMethod]
  public MyObject MyMethod(int id) 
  {
    return new MyObject();
  }
}
Nick Craver
Exactly what I was going to look at in the code :)
Mark Schultheiss
If I do a Post I get 403 Forbidden error. If I do a json and get I get a 500 Internal Server Error. But if I do a jsonp and get I get the results but it's wrapped in xml rather than just straight json. I am going to try to do a $.getJSON() to see if that helps.
Cheryl
@Cheryl - What internal server error are you getting? Your event log should say, or attach a debugger.
Nick Craver