2011-08-09 28 views
2

我正在使用Jquery Ajax在我的表單中設置Label和ListBox的值。我意識到值由函數正確設置。但在此之後,頁面只會刷新所有先前設置的值。這是爲什麼發生? Iam是Jquery/Ajax的新成員。我在這裏錯過了任何基礎知識嗎?提前致謝。用ASP.NET WebMethod刷新整個頁面的Jquery AJAX

蔭粘貼整個代碼

 $(document).ready(function() { 
      $('#Button1').bind('click', function clk() { 
       $.ajax({ 
        type: "POST", 
        url: "WebForm5.aspx/TestMethod", 
        data: "{}", 
        contentType: "application/json; charset=utf-8", 
        dataType: "json", 
        success: function (result) { 
         alert(result.d.ListBox.length); 
         for (var i = 0; i < result.d.ListBox.length; i++) { 
          alert(result.d.ListBox[i]); 
          $(document.createElement("option")).attr("value", result.d.ListBox[i]).html(result.d.ListBox[i]) 
    .appendTo('#<%=ListBox1.ClientID %>'); 

          $('#Label1').text(result.d.MyProperty); 
         } 
        } 
       }); 
      }) 
     });     

回答

7

Button1在你的代碼是一個ASP按鈕,這是一個提交按鈕。當你點擊它時,它會提交頁面並刷新整個頁面。如果您想停止按鈕上提交的頁面,請點擊return false,它將起作用。

$('#Button1').bind('click', function clk() { 
       $.ajax({ 
        type: "POST", 
        url: "WebForm5.aspx/TestMethod", 
        data: "{}", 
        contentType: "application/json; charset=utf-8", 
        dataType: "json", 
        success: function (result) { 
         alert(result.d.ListBox.length); 
         for (var i = 0; i < result.d.ListBox.length; i++) { 
          alert(result.d.ListBox[i]); 
          $(document.createElement("option")).attr("value", result.d.ListBox[i]).html(result.d.ListBox[i]) 
    .appendTo('#<%=ListBox1.ClientID %>'); 

          $('#Label1').text(result.d.MyProperty); 
         } 
        } 
       }); 

    return false; 
      }) 
+0

..謝謝..完美的工作......請你指教我爲什麼發生這種情況,以及如何「回報假」的伎倆? – Ananth

+1

在我的回答中加入瞭解釋一下。 – ShankarSangoli

+0

完美..謝謝:) – Ananth