如果要使用WFC的REST類型的服務,而不是Web服務的.asmx你可以實現從你的問題你的所有要求。但是使用帶有JSON的.asmx webservice作爲輸出需要,您至少使用contentType: 'application/json'
。在不同的地方你可以找到一個理由 - 安全原因(參見JSON劫持)。
也許'x-www-form-urlencoded'不是你真正的問題。如果使用dataType: "json"
,參數也將以「test1 = value1 & test2 = value2」的形式發送!唯一的區別是,所有的值都應該是JSON編碼的。而jQuery 不會對數據進行JSON編碼。 (您可以查看jQuery代碼。)主要區別僅在於「Accept:application/json」將在請求頭中明確設置。
看看我最近寫的JQuery ajax call to httpget webmethod (c#) not working。在這篇文章中被問到GET請求的例子。但它幾乎是一樣的。唯一的區別是,編碼後數據將被追加到URL(用於GET請求)。對於POST請求數據將發送正文。順便說一句,如果一個設置「processData:false」(見http://api.jquery.com/jQuery.ajax/)GET數據也將被髮送到主體內部。所以請閱讀我的代碼示例JQuery ajax call to httpget webmethod (c#) not working。我希望你能得到你如何實現你的想法。
我認爲你在編碼複雜數據時遇到了問題。asmx webservice調用。這裏是例如用 「複雜」 的數據:
[WebMethod]
[ScriptMethod (UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public OutputData AjaxGetMore (InputData input) {
return new OutputData() {
id = input.id,
message = new List { "it's work!", "OK!" },
myInt = new int[] { input.myInt[0] + 1, input.myInt[1] + 1, 20, 75 },
myComplexData = new InternalData() { blaBla = "haha", iii = new int[] { 1, 2, 3, 4, 5 } }
};
}
其中(來自JSON插件$.toJSON
)
public class InternalData {
public string blaBla { get; set; }
public int[] iii { get; set; }
}
public class OutputData {
public string id { get; set; }
public List message { get; set; }
public int[] myInt { get; set; }
public InternalData myComplexData { get; set; }
}
public class InputData {
public string id { get; set; }
public int[] myInt { get; set; }
public InternalData data { get; set; }
}
,並在客戶端
var myData = { id: "li1234", myInt: [100, 200], data : {blaBla: "Hahhh!", iii: [10,20,30]}}
var myDataForjQuery = {input:$.toJSON(myData)};
$.ajax({
type: "GET",
url: "/Service1.asmx/AjaxGetMore", // + idAsJson,
data: myDataForjQuery, // idAsJson, //myData,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(msg) {
// var msg = {__type: "Testportal.outputData", id: "li1234", message: "it's work!", myInt:101}
alert("message=" + msg.d.message + ", id=" + msg.d.id + ", myInt=" + msg.d.myInt);
},
error: function(res, status) {
if (status ==="error") {
// errorMessage can be an object with 3 string properties: ExceptionType, Message and StackTrace
var errorMessage = $.parseJSON(res.responseText);
alert(errorMessage.Message);
}
}
});
您可以修改這個例子到HTTP POST,如果你想。
還有一個小建議。如果你使用jQuery 1.4.x,你可以嘗試使用'none'作爲dataType。請參閱文檔:「如果沒有指定,jQuery將根據響應的MIME類型智能地嘗試獲取結果(XML MIME類型將生成XML,在1.4 JSON中將生成一個JavaScript對象,在1.4腳本中將執行腳本,和其他任何會返回一個字符串)」
問候
嗨奧列格, 感謝您的長時間迴應! !經過大量嘗試,我斷定從我的web服務返回json數據的唯一方法是將contentType設置爲'application/json',如上所述。我決定不採用這種方法,因爲我不想爲了發佈而將序列化爲簡單表單的路徑,特別是因爲在所有瀏覽器中默認情況下不支持任何功能來執行此操作。最後,我決定最好的方法是使用ASP.NET MVC,它通過Controller中的JSONResult提供'開箱即用'json支持。感謝您的幫助:) – 2010-04-21 00:38:33
歡迎您。我也喜歡並使用ASP.NET MVC。我決定將所有業務邏輯放在WFC內部作爲數據提供。這是純粹的建築決策。但是對於你來說項目ASP.NET MVC可能是最好的。 ASP.NET MVC從3種方式中是最靈活的:WFC,MVC和.asmx webservice。 Goog運氣和軟件開發的樂趣! – Oleg 2010-04-21 01:11:35