代码之家  ›  专栏  ›  技术社区  ›  Andy

jquery ajax对asp.net webmethod的调用经常出错

  •  1
  • Andy  · 技术社区  · 16 年前

    我的default.aspx.cs中有一个非常简单的ajax方法,如下所示:

    public partial class _Default : System.Web.UI.Page 
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
    
        [WebMethod]
        public static string GetDate()
        {
            return DateTime.Now.ToString();
        }
    }
    

    default.aspx如下所示:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>Untitled Page</title>
        <script type="text/javascript" src="http://192.168.1.2/tizma.com/js/jquery-1.3.2.min.js"></script>
        <script type="text/javascript">   
            $(document).ready(function() {
              // Add the page method call as an onclick handler for the div.
              $("#Result").click(function() {
                $.ajax({
                  type: "POST",
                  url: "Default.aspx/GetDate",
                  data: "{}",
                  contentType: "application/json; charset=utf-8",
                  dataType: "json",
                  success: AjaxSucceeded,
                  error: AjaxFailed
                });
              });
            });
    
            function AjaxSucceeded(result)
            {
                alert(result.d);
            }
    
            function AjaxFailed(result)
            {
                alert(result.status + " " + result.statusText);
            }
        </script>
    </head>
    <body>
        <div id="Result">Click me</div>
    </body>
    </html>
    

    问题是,当我单击div时,ajax错误函数就是以200状态调用的所有函数。

    我做错什么了?

    1 回复  |  直到 16 年前
        1
  •  -2
  •   grenade    16 年前

    不确定这是否导致了问题,但您有一行代码:

    data: "{}",
    

    应改为:

    data: {},
    

    或者,您可以省略该行,因为它是方法调用的可选参数。您当前正在将其设置为字符串值,而它实际需要WebMethod的参数,这可能会导致问题。

    另外,这几行是:

    contentType: "application/json; charset=utf-8",
    dataType: "json",
    

    对我来说似乎没有必要,因为对于初学者来说,您的webmethod实际上返回json并不明显。我想它只是返回一个字符串。试着把这三条线连在一起,看看它是否开始工作了。

    推荐文章