代码之家  ›  专栏  ›  技术社区  ›  Brian Webster

ASP.NET 4.0-使用Jquery,如何调用codebhind函数并将数据返回给客户端?

  •  1
  • Brian Webster  · 技术社区  · 13 年前

    当我单击以下div时:

     <div id="Result">Click here for the time.</div>
    

     <WebMethod()> _
     Public Shared Function GetDate() As String
         Return DateTime.Now.ToString()
     End Function
    

    我需要用GetDate()函数返回的字符串填充div的内部。我认为应该使用类似的代码:

    <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: "test.aspx/GetDate",
                    data: "{}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        // Replace the div's content with the page method's return.
                        $("#Result").text(msg.d);
                    }
                });
            });
        });
    </script>
    

    我已经从这个网站上提取了这个例子: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/

    下面是当我单击div时firebug控制台告诉我的:

     POST http://admin/Default.aspx   GetDate   404 Not Found   -18ms
    

    编辑:注意:test.aspx/GetDate必须与aspx页名和函数名匹配!

    1 回复  |  直到 13 年前
        1
  •  3
  •   Carson63000    13 年前
    <WebMethod()> _
    Public Shared Function GetDate() As String
        Return DateTime.Now.ToString()
    End Function
    

    必须“共享”(“静态”在C#)