2010-03-24 115 views
1

這是我的下面Javascript我想顯示載入記錄並顯示新的記錄添加到數據庫Javascript何時顯示結果

showrecords();顯示數據庫中的記錄,我可以把它放在我的代碼中,它可以正常工作。

$(document).ready(function() 
{ 
    //showrecords() 

    function showrecords() 
    { 
     $.ajax({ 
      type: "POST", 
      url: "demo_show.php", 
      cache: false, 
      success: function(html){ 

       $("#display").after(html); 

       document.getElementById('content').value=''; 
       $("#flash").hide(); 

      } 

     }); 
    } 

    $(".comment_button").click(function() { 

     var element = $(this); 
     var test = $("#content").val(); 
     var dataString = 'content='+ test; 

     if(test=='') 
     { 
      alert("Please Enter Some Text"); 

     } 
     else 
     { 
      $("#flash").show(); 
      $("#flash").fadeIn(400) 
       .html('<img src="http://tiggin.com/ajax-loader.gif" align="absmiddle">&nbsp;<span class="loading">Loading Comment...</span>'); 


      $.ajax({ 
       type: "POST", 
       url: "demo_insert.php", 
       data: dataString, 
       cache: false, 
       success: function(html){ 


        // $("#display").after(html); 
        document.getElementById('content').value=''; 
        $("#flash").hide(); 

        //Function for showing records 
        //showrecords(); 

       } 
      }); 
     } 

    return false; 
    }); 
}); 
+0

你的代碼打破了什麼地方?這有點模糊...... – 2010-12-08 19:38:50

回答

0

雖然不建議污染全局命名空間。這是我爲你的代碼推薦的內容。將showRecords()移出Document ready函數,並將更新ajax代碼重構爲另一個函數'updateRecords()'。只有文檔就緒功能內的事件綁定。

您可以返回整個註釋作爲POST'demo_insert.php'服務的響應,並在更新服務成功回調中調用'showRecords()'。

+0

在這種情況下事件綁定是什麼。 你能解釋一下你說的高招嗎,因爲我是一個JavaScript新手的升技 Thankyou Pete – Pete 2010-03-25 10:14:28

0

我粘貼下面(未經測試)的代碼,我認爲應該完成這項工作。爲了調用函數,必須在可訪問區域中定義它們,無論是在「全局」(可以從任何地方調用)命名空間中,如我在下面所做的或作爲另一個對象的一部分。

您還需要確保在嘗試調用它們之前定義了您的函數,因爲所有操作都以自頂向下的方式進行。

function showrecords() { 
    $.ajax({ 
    type: "POST", 
    url: "demo_show.php", 
    cache: false, 
    success: function (html) { 

     $("#display").after(html); 

     $('content').val(''); 
     $("#flash").hide(); 

    } 

    }); 
} 
function addComment() { 
    var test = $("#content").val(); 
    var dataString = 'content=' + test; 

    if (test == '') { 
    alert("Please Enter Some Text"); 
    } 
    else { 
    $("#flash").show(); 
    $("#flash").fadeIn(400) 
       .html('<img src="http://tiggin.com/ajax-loader.gif" align="absmiddle">&nbsp;<span class="loading">Loading Comment...</span>'); 

    $.ajax({ 
     type: "POST", 
     url: "demo_insert.php", 
     data: dataString, 
     cache: false, 
     success: function (html) { 
     //$("#display").after(html); 
     $('content').val(''); 
     $("#flash").hide(); 
     //Function for showing records 
     showrecords(); 
     } 
    }); 
    } 
} 

$(document).ready(function() { 
    showrecords() 

    $(".comment_button").click(function() { 
    addComment(); 
    return false; 
    }); 
});