调用简单的AJAX WebMethod总会导致"失败"打回来

时间:2014-06-12 06:01:53

标签: c# jquery ajax json 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不适合此情况。我不知道。

3 个答案:

答案 0 :(得分:2)

此:

public static string InsertCV(string edu)

期望一个名为edu的参数类型为string。你的AJAX调用是传入一个未命名的JavaScript对象,它是而不是一个字符串。尝试解析请求的框架代码永远不会与您的InsertCV方法匹配,最终会放弃500 - Internal Server Error结果。

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

答案 1 :(得分:1)

我找到了解决问题的方法。

以下是代码:

as cs page:

[WebMethod]
public static string InsertCV(object education)
{
   return "";
}

并且用于调用此方法:

var edu = { "education": [{ "university": "111", "speciality": "222", "faculty": "333", "degree": "444", "start": "555", "end": "666"}] }

   var post = $.ajax(
   {
      type: "POST",
      data:  JSON.stringify(edu),
      url: "ServiceTest.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");
   });

如果这对您有帮助,请标记为正确。

感谢。

答案 2 :(得分:0)

正如@ user2864740所问,您的方法InsertCV没有做任何事情。我建议首先通过在InsertCV方法中设置断点来测试你的webmethod,看看是否在浏览时遇到这个问题。其次,从您的AJAX post方法发送JSON数组,但在InsertCV方法中,您只需要一个字符串。这必须匹配。当您可以从AJAX调用触发WebMethod时,继续并添加处理以写入后端数据库