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

时间:2022-04-26 01:25:45

I am using Encosia's sample from his website on how to use ajax call

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

When I click on the div it's working fine and when I replace button instead of div it's refreshing the whole page and I don't find any errors in firebug.

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

Here is my code:

这是我的代码:

Script:

<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>

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>

Code-behind:

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

1 个解决方案

#1


5  

What most probably happens is - the button submits the page so the pages gets reloaded. I had this problem before in some browsers. You need to specify type="button" attribute.

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

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

#1


5  

What most probably happens is - the button submits the page so the pages gets reloaded. I had this problem before in some browsers. You need to specify type="button" attribute.

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

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