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