簡體   English   中英

表單提交后更新div內容而無需重新加載頁面

[英]Updating div content after form submit without page reload

好吧,我有一個彈出窗口,顯示一些有關客戶的注釋。 內容(注釋)通過ajax顯示(通過ajax獲取數據)。 我也有一個add new按鈕來添加新筆記。 該注釋也添加了ajax。 現在,在將注釋添加到數據庫之后出現了問題。

如何刷新顯示筆記的div

我已經閱讀了多個問題,但無法獲得答案。

我的代碼獲取數據。

<script type="text/javascript">
    var cid = $('#cid').val();
    $(document).ready(function() {
        $.ajax({    //create an ajax request to load_page.php
            type: "GET",
            url: "ajax.php?requestid=1&cid="+cid,             
            dataType: "html",   //expect html to be returned                
            success: function(response){                    
                $("#notes").html(response); 
                //alert(response);
            }
        });
    });
</script>

DIV

<div id="notes">
</div>

我的代碼提交表單(添加新注釋)。

<script type="text/javascript">
    $("#submit").click(function() {
        var note = $("#note").val();
        var cid = $("#cid").val();
        $.ajax({
            type: "POST",
            url: "ajax.php?requestid=2",
            data: { note: note, cid: cid }
        }).done(function( msg ) {
            alert(msg);
            $("#make_new_note").hide();
            $("#add").show();
            $("#cancel").hide();
            //$("#notes").load();
        });
    });
</script>

我嘗試了load ,但是沒有用。

請指引我正確的方向。

創建一個函數來調用ajax並從ajax.php獲取數據,然后在需要更新div時就調用該函數:

<script type="text/javascript">
$(document).ready(function() {
  // create a function to call the ajax and get the response
  function getResponse() {
    var cid = $('#cid').val();
    $.ajax({ //create an ajax request to load_page.php
      type: "GET",
      url: "ajax.php?requestid=1&cid=" + cid,
      dataType: "html", //expect html to be returned                
      success: function(response) {
        $("#notes").html(response);
        //alert(response);
      }

    });
  }
  getResponse(); // call the function on load


  $("#submit").click(function() {
    var note = $("#note").val();
    var cid = $("#cid").val();
    $.ajax({
      type: "POST",
      url: "ajax.php?requestid=2",
      data: {
        note: note,
        cid: cid
      }
    }).done(function(msg) {
      alert(msg);
      $("#make_new_note").hide();
      $("#add").show();
      $("#cancel").hide();}
      getResponse(); // call the function to reload the div

    });
  });
});

</script>

您需要為jQuery load()函數提供一個URL,以告訴您從何處獲取內容。 因此,要加載注釋,您可以嘗試以下操作:

$("#notes").load("ajax.php?requestid=1&cid="+cid);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM