Simple ajax call not working with button click

两盒软妹~` 提交于 2019-12-07 13:11:50

问题


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

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.

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:


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.

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



来源:https://stackoverflow.com/questions/10567951/simple-ajax-call-not-working-with-button-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!