下面应该调用WebMethod的参数什么来获取客户端发送的json数组?我使用了 name
,但没有用。
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);
这是将它发送到 Web 方法的 jquery ajax。
$("#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");
}
});
这是网络方法
[System.Web.Services.WebMethod]
public static string GetDetails(string name)
{
var x=name;
return "";
}
最佳答案
你必须重写你的数据初始化:
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
$.ajax({
type: "POST",
url: "Default.aspx/GetDetails",
data: JSON.stringify({ name: employees }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert("Wrong");
}
});
function OnSuccess(response) {
alert("Sent");
}
在服务器端使用对象参数类型:
[System.Web.Services.WebMethod]
public static string GetDetails(object name)
{
var x=name;
return "";
}
编辑: 正如@Felix Kling 指出的那样,不需要删除引号。
关于javascript - 使用 JQuery Ajax 将 Json 对象数组发送到 Web 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25919212/