使用JQueryAjax将Json对象数组发送到Web方法
Sending array of Json objects to Web Method using JQuery Ajax
下面应该调用什么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);
这是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 "";
}
您必须重写数据初始化:
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所指出的,不需要删除引号。
您只需将web方法更改为:
[System.Web.Services.WebMethod]
public static string GetDetails(object name)
{
var x=name;
return "";
}
相关文章:
- PageMethods调用使用1参数成功,但在2上失败(未知web方法)
- Web方法只有在标记为静态时才有效,否则就不起作用;t
- Ajax 对 Web 方法 asp.net 调用不会触发
- 如何在 asp.net 中更改文本框的事件时调用Web方法
- 如何从外部项目调用 Web 方法
- 无法从母版页调用代码页中的 Web 方法
- 警报消息在 Ajax Web 方法中无法正常工作
- Web方法未在FlexiGrid中触发
- 调用服务器端从 JavaScript 继承了 C# Web 方法
- 使用 jQuery.ajax() 访问 c# WebMethod 会得到“未知的 Web 方法”
- asmx中Web方法的Ajax方法未启动
- asp.net web方法中ajax回调后,对象属性为null
- AJAX调用C#Web方法以返回列表
- jsTree-使用AJAX/C#Web方法动态填充树
- aspx页面中的Web方法未执行
- 使用JavaScript中的异步Web方法返回值触发/阻止页面事件
- javascript.net Web方法未执行
- jquery AJAX对web方法的调用未运行错误函数
- 如何将参数从原型传递到web方法
- Web方法不会调用,但不会出错