use*_*174 6 asp.net ajax jquery json
我使用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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
ASP.NET代码
[WebMethod]
public static void SetStudentInfo(object students)
{
//Here I want to iterate the 4 objects and to print their name and id
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
"{"消息":"无效的JSON原语:学生.","StackTrace":"在System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32深度)的System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()处在System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String输入,Int32 depthLimit,JavaScriptSerializer序列化程序)处于System的System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer序列化程序,字符串输入,类型类型,Int32 depthLimit). System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest中的Web.Script.Serialization.JavaScriptSerializer.Deserialize [T](字符串输入)(HttpContext上下文,位于System.Web.Script.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context,WebServiceMethodData methodData)的System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData,HttpContext context)中的JavaScriptSerializer序列化程序","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);
}
});
Run Code Online (Sandbox Code Playgroud)
将整个JSON作为字符串传递,如下所示:
data: '{variable: "value"}'
Run Code Online (Sandbox Code Playgroud)
如果我试图通过它,我总是会收到错误.
您实际上并没有将 json 发送到服务器,要发送 json,只需传递 data 属性的 json 字符串即可。
data: JSON.stringify(jsonObjects),
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25128 次 |
| 最近记录: |