开发者

Ajax query to my webservices is returning xml in my json

I am having this exact problem as raised in this question

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


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();
  }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜