下面的代码是我的服务器端代码。 (C#)
[WebMethod]
public static string InsertCV(string edu)
{
return "";
}
下面的代码是我的客户端代码。 (ASP.NET)
var edu = {"education":[{"university":"111","speciality":"222","faculty":"333","degree":"444","start":"555","end":"666"}]}
var post = $.ajax(
{
type: "POST",
data: edu,
url: "Add_CV.aspx/InsertCV",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false
})
post.done(function (data, teStatus, jqXHR) {
if (data.d == "")
{ alert("ok"); }
});
post.fail(function (jqXHR, e) {
alert("error");
});
我想使用ajax post方法将用户数据发送到服务器。但每次 post.fail()
函数执行时。
请帮我看看我的错误在哪里。
可能在服务器端 InsertCV(string edu)
, string
不适合这种情况。我不知道。
最佳答案
这个:
public static string InsertCV(string edu)
需要一个名为edu
的参数,其类型为string
。您的 AJAX 调用会传入一个未命名的 JavaScript 对象,它不是一个字符串。尝试解析请求的框架代码根本不会与您的 InsertCV
方法匹配,并最终放弃并返回 500 - 内部服务器错误
结果。
要将这样的复杂结构传递到 WebMethod
中,您需要定义一个兼容的 .NET 类来反序列化。例如:
// outer type for the parameter
public class EduType
{
public Education[] education;
// inner type for the 'education' array
public class Education
{
public string university;
public string speciality;
public string faculty;
public string degree;
public string start;
public string end;
}
}
[WebMethod]
public static string InsertCV(EduType edu)
{
return edu == null ? "null" : string.Format("{0} Items", edu.education.Length);
}
如果 JSON 字符串将反序列化为这种格式,那么应该调用此方法。
关于c# - 调用简单的 AJAX WebMethod 总是会导致 "fail"回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24177421/