我在使用 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 代码
[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"}"
最佳答案
我知道这是一个老问题,但如果有人来这里寻求答案,这里就是解决方案;
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);
}
});
关于asp.net - 如何使用 Ajax 和 ASP.NET WebMethod 传递 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13449137/