2013-07-02 36 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; 
    }