2012-05-12 54 views
3

我如何使用Ajax調用簡單的Ajax調用不使用按鈕工作單擊

使用Encosia's樣品從他的網站。當我在DIV上點擊它的正常工作,當我更換,而不是DIV按鈕它刷新整個頁面,並且我在螢火蟲中找不到任何錯誤。

這裏是我的代碼:

腳本:

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

代碼隱藏:

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

回答

5

最可能發生的事情是 - 按鈕提交頁面以便頁面重新加載。我之前在某些瀏覽器中遇到過這個問題。 您需要指定type="button"屬性。

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

+0

@安德烈 - 謝謝你正確識別它。它現在工作。 – coder

+0

我很高興它幫助:) – Andrey