2011-02-10 50 views
1

我試圖使用jQuery這樣調用PageMethodPageMethods,jQuery和JSON

[WebMethod] 
public stataic string WebMethod(PostData data) 
{ 
    //DO WORK 
    return "a"; 
} 

PostData類如下:

public class PostData 
{ 
    public string Guid{get;set;} 
    public string Action{get;set;} 
    public string Id{get;set;} 
} 

我打電話的方法從jQuery的是這樣的:

$.ajax({ 
    type="POST", 
    url: 'url', 
    data: JSON.stringify(b), 
    contentType: "application/json;charset=utf-8", 
    dataType: "json", 
    success: function (msg) { 
     var t = $(c).html(); 
     $(c).html(t + "<br/>" + $.evalJSON(msg.d)); 
    }, 
    error: function (x, y) { 
     var t = $(c).html(); 
     $(c).html(t + "<br/>" + $.evalJSON(x.responseText).Message); 
    } 
}); 

其中b是這樣的:{"PostData":{"Guid":"b61dce32-690b-4409-b51a-a6012462e54e","Action":"Testing","Id":"3"}}

我得到這個錯誤:

Invalid web service call, missing value for parameter: 'data'. 

如果我不叫JSON.stringyfy然後我得到這個錯誤:

Invalid JSON primitive: PostData. 

我已經試過這也{"Guid":"b61dce32-690b-4409-b51a-a6012462e54e","Action":"Testing","Id":"3"}但仍獲得任意

Invalid JSON primitive 'Guid' 

or

Invalid web service call, missing value for parameter: 'data'. 

取決於我是否撥打JSON.stringify或不。

我也試過,

[WebMethod] 
public static string WebMethod(string data) 

,但沒有得到哪裏。

回答

2

JSON中的第一個分層對象名稱應該與您的webservice參數名稱相同。

{"data": {"Guid":"b61dce32-690b-4409-b51a-a6012462e54e","Action":"Testing","Id":"3"} } 
+0

是的,我知道我在做一些愚蠢的事情,但沒有能夠釘住它。謝謝@ jerone。 – TheVillageIdiot 2011-02-10 08:22:07

0

試試這個,

 var params = {"PostData":{"Guid":"b61dce32-690b-4409-b51a-a6012462e54e","Action":"Testing","Id":"3"}}; 
     var yourdata = jQuery.param(params); 

yourdata

爲您的數據,而不是JSON.stringify(B)。

+0

nope @Furqan`jQuery.param`將其轉換爲編碼字符串。我實際上需要`data:`作爲對象名稱。 – TheVillageIdiot 2011-02-10 08:45:43