jQuery 如何使用 Ajax 和 ASP.NET WebMethod 传递 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13449137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass JSON object using Ajax with ASP.NET WebMethod
提问by user829174
I have a problem with passing a JSON object using Ajax and ASP.NET WebMethods
我在使用 Ajax 和 ASP.NET WebMethods 传递 JSON 对象时遇到问题
function setStudentInfo() {
var jsonObjects = [
{ id: 1, name: "mike" },
{ id: 2, name: "kile" },
{ id: 3, name: "brian" },
{ id: 1, name: "tom" }
];
$.ajax({
type: "POST",
url: "ConfigureManager.aspx/SetStudentInfo",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
data: { students: JSON.stringify(jsonObjects) },
success: function (result) {
alert('success');
},
error: function (result) {
alert(result.responseText);
}
});
}
ASP.NET code
ASP.NET 代码
[WebMethod]
public static void SetStudentInfo(object students)
{
//Here I want to iterate the 4 objects and to print their name and id
}
I am getting the following error:
我收到以下错误:
"{"Message":"Invalid JSON primitive: students.","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject() at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth) at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer) at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit) at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input) at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer) at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context) at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}"
"{"Message":"无效的 JSON 原语:学生。","StackTrace":" 在 System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject() 在 System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 深度)在 System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer) 在 System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit) 在 System. Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input) at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context,JavaScriptSerializer 序列化程序) 在 System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context) 在 System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.参数异常"}"
回答by Yatrix
Pass your entire JSON as a string, like this:
将整个 JSON 作为字符串传递,如下所示:
data: '{variable: "value"}'
I always get an error if I try to pass it as you have.
如果我尝试像您一样传递它,我总是会收到错误消息。
回答by Martin-Brennan
You are getting that error because a single Object is expected but your code is expecting a List of Objects. This can be a bit tricky sometimes. To make the data transfer easier, you should create a class with properties for the type of object you want to pass to the WebMethod, because it seems to be easier for ASP.NET to parse that. For example:
您收到该错误是因为需要一个对象,但您的代码需要一个对象列表。这有时可能有点棘手。为了使数据传输更容易,您应该创建一个具有要传递给 WebMethod 的对象类型的属性的类,因为 ASP.NET 解析它似乎更容易。例如:
public class Student
{
private string _name;
private int _id;
public string name {
get { return _name; }
set { _name = value; }
}
public int id {
get { return _id; }
set { _id = value; }
}
}
And then your WebMethod will change to accept a List of Student Class Objects, like so:
然后您的 WebMethod 将更改为接受学生类对象列表,如下所示:
[WebMethod]
public static void SetStudentInfo(List<Student> Students)
{
foreach (Student s in Students)
{
//Do whatever here System.Console.WriteLine(s.name);
}
}
Then all you need to do is slightly change your Ajax call like so:
然后你需要做的就是稍微改变你的 Ajax 调用,如下所示:
function setStudentInfo() {
var jsonObjects = [
{ id: 1, name: "mike" },
{ id: 2, name: "kile" },
{ id: 3, name: "brian" },
{ id: 1, name: "tom" }
];
$.ajax({
type: "POST",
url: "ConfigureManager.aspx/SetStudentInfo",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
data: { Students: JSON.stringify(jsonObjects) },
success: function (result) {
alert('success');
},
error: function (result) {
alert(result.responseText);
}
});
}
回答by c-sharp
I know its an old question but if someone gets here for an answer here's the solution;
我知道这是一个老问题,但如果有人来这里寻求答案,这就是解决方案;
var jsonObjects=[
{ id: 1, name: "mike" },
{ id: 2, name: "kile" },
{ id: 3, name: "brian" },
{ id: 1, name: "tom" }
];
$.ajax({
type: "POST",
url: "ConfigureManager.aspx/SetStudentInfo",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
data: JSON.stringify({ students: jsonObjects }),
success: function (result) {
alert('success');
},
error: function (result) {
alert(result.responseText);
}
});
回答by Arun
Try this code:
试试这个代码:
function setStudentInfo() {
var jsonObjects = {"students" : [
{ id: 1, name: "mike" },
{ id: 2, name: "kile" },
{ id: 3, name: "brian" },
{ id: 1, name: "tom" }
]};
$.ajax({
type: "POST",
url: "ConfigureManager.aspx/SetStudentInfo",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
data: JSON.stringify(jsonObjects),
success: function (result) {
alert('success');
},
error: function (result) {
alert(result.responseText);
}
});
}
}
回答by Musa
You aren't actually sending json to the server, to send json just pass a json string for the data property.
您实际上并没有将 json 发送到服务器,发送 json 只需为 data 属性传递一个 json 字符串。
data: JSON.stringify(jsonObjects),