简单的ajax调用无法使用按钮单击

cod*_*der 3 asp.net ajax click button

我正在他的网站上使用Encosia的样本,了解如何使用ajax调用

当我点击div它工作正常,当我更换按钮而不是div时,它刷新了整个页面,我没有在firebug中发现任何错误.

这是我的代码:

脚本:

<script type="text/javascript">
    $(document).ready(function () {
        // Add the page method call as an onclick handler for the div.
        $("#getdate").click(function () {
            $.ajax({
                type: "POST",
                url: "Default.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").html(msg.d);
                }
            });
        });
    });
</script>
Run Code Online (Sandbox Code Playgroud)

HTML:

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>
<div id="Result">Click here for the time.</div>
<button id="getdate" value="Click Me">ClickMe</button>
Run Code Online (Sandbox Code Playgroud)

代码隐藏:

<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
Public Shared Function GetDate() As String
     Return DateTime.Now.ToString()
End Function
Run Code Online (Sandbox Code Playgroud)

And*_*rey 5

最可能发生的是 - 按钮提交页面以便重新加载页面.我以前在某些浏览器中遇到过这个问题.您需要指定type="button"属性.

http://www.w3schools.com/tags/tag_button.asp