调用简单的AJAX WebMethod始终会导致“失败”回调

用户名

下面的代码是我的服务器端代码。(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 - Internal Server Error结果。

要将这样的复杂结构传递给A,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字符串将反序列化为这种格式,则应调用此方法。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章