AJAX到web方法不返回JSON

我使用AJAX从我的js文件中调用aspx页面中的web方法。 我已将方法设置为[WebMethod],页面inheritance自System.Web.Ui.Page类。 它仍然没有将JSON格式返回给我的调用ajax函数。

这是js文件中的AJAX调用:

$.ajax({ type: "POST", url: "/WebServiceUtility.aspx/CustomOrderService", data: "{'id': '2'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (message) { ShowPopup(message); } }); function ShowPopup(result) { if (result.d != "") { request=result.d; } } 

这是web方法:

 using System; using System.IO; using System.Net; using System.Text; using System.Web.Services; namespace SalesDesk.Global { public partial class WebServiceUtility : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } [WebMethod] public string CustomOrderService(string id) { string result; // code logic which sets the result value result="some value"; return result; } } } 

当我在Firefox浏览器中按F12并检查网络调用中的请求/响应时,我根本看不到JSON选项卡。 相反,我看到HTML标签。

我是否需要专门设置任何响应标头? 我到底错过了什么?

编辑:找到一个解决方案。 最终,有效的是带有回调函数的$ .getJSON()调用作为成功方法,下面是网页中的代码

  result = "..."; Response.Clear(); Response.ContentType = "application/json"; Response.Write(result); Response.Flush(); Response.End(); 

谢谢大家的宝贵建议。

试试这个

  [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public string CustomOrderService(string id) { string result; // code logic which sets the result value result="some value"; return result; } 

使用以下内容装饰您的CustomOrderService方法:

 [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 

另外,将您的退货数据更改为:

 return new JavaScriptSerializer().Serialize(result); 

我唯一看到的缺点是使方法静态。

阅读这篇文章

http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

使用静态字符串

  [WebMethod] public static string CustomOrderService(string id) { string result; // code logic which sets the result value result="some value"; return result; }