2013-07-02 32 views
1

我在使用AJAX从我的js文件调用aspx页面中的web方法。我已经将该方法设置为[WebMethod],并且该页面从System.Web.Ui.Page类继承。它仍然不会将JSON格式返回给我的调用ajax函数。AJAX to web方法不返回JSON

这里是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; 
     } 

    } 
} 

当我按下F12在Firefox浏览器,并检查网络的呼叫请求/响应,我根本没有看到JSON选项卡。相反,我看到HTML标签。

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

编辑:找到一个解决方案。归根结底,工作是一个回调函数的成功方法$ .getJSON()调用以下是在网页中所有您的宝贵建议

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

感谢代码。

+0

您需要在服务器上设置Content-type:application/json'头。您还需要返回适当的JSON字符串。 – 2013-07-02 10:41:43

回答

5

试试这个

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

      return result; 
     } 
5

装饰你的CustomOrderService法:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 

此外,改变你的回报数据:

return new JavaScriptSerializer().Serialize(result); 
+0

这会自动将C#对象转换为JSON吗? –

0

使用静态字符串

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

     return result; 
    }