下面調用WebMethod的參數來獲取從客戶端發送的json數組?我用name
,但它沒有奏效。使用JQuery Ajax發送Json對象數組到Web方法
var employees = {
"accounting": [ // accounting is an array in employees.
{
"firstName": "", // First element
"lastName": "Doe",
"age": 23
},
{
"firstName": "Mary", // Second Element
"lastName": "Smith",
"age": 32
}
], // End "accounting" array.
"sales": [ // Sales is another array in employees.
{
"firstName": "Sally", // First Element
"lastName": "Green",
"age": 27
},
{
"firstName": "Jim", // Second Element
"lastName": "Galley",
"age": 41
}
] // End "sales" Array.
} // End Employees
var toServer = JSON.stringify(employees);
這是jQuery的ajax發送給Web方法。
$("#sendtoServer").click(function() {
$.ajax({
type : "POST",
url : "Default.aspx/GetDetails",
data : '{name: "' + toServer + '" }',
contentType : "application/json; charset=utf-8",
dataType : "json",
success : OnSuccess,
failure : function (response) {
alert("Wrong");
}
});
function OnSuccess(response) {
alert("Sent");
}
});
這是Web方法
[System.Web.Services.WebMethod]
public static string GetDetails(string name)
{
var x=name;
return "";
}
如果您告訴服務器您要發送JSON,則實際上必須發送JSON。 ''{name:''+ toServer +'「}」'不是JSON。也許只需要'data:toServer'。 – 2014-09-18 17:50:18