Ajax query to my webservices is returning xml in my json

前提是你 提交于 2019-12-25 00:49:56

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/3357932/ajax-query-to-my-webservices-is-returning-xml-in-my-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!