How to pass JSON object using Ajax with ASP.NET WebMethod
我有一个使用Ajax和ASP.NET WebMethods传递JSON对象的问题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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码
1 2 3 4 5 | [WebMethod] public static void SetStudentInfo(object students) { //Here I want to iterate the 4 objects and to print their name and id } |
我收到以下错误:
"{"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"}"
将整个JSON作为字符串传递,如下所示:
1 | data: '{variable:"value"}' |
如果我试着像你一样通过它,我总是会出错。
我知道这是一个古老的问题,但如果有人来这里寻求答案,这就是解决办法;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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); } }); |
您收到该错误是因为需要单个对象,但您的代码需要一个对象列表。有时候会有点棘手。为了使数据传输更容易,应该为要传递给WebMethod的对象类型创建一个具有属性的类,因为ASP.NET似乎更容易解析该类。例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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; } } } |
然后,您的webmethod将更改为接受学生类对象列表,如下所示:
1 2 3 4 5 6 7 8 | [WebMethod] public static void SetStudentInfo(List<Student> Students) { foreach (Student s in Students) { //Do whatever here System.Console.WriteLine(s.name); } } |
然后,您需要做的就是像这样稍微更改Ajax调用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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); } }); } |
试试这个代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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); } }); |
}
实际上您并没有向服务器发送JSON,要发送JSON,只需为数据属性传递一个JSON字符串。
1 | data: JSON.stringify(jsonObjects), |