表单提交后更新div内容而不重新加载页面

时间:2015-08-08 18:02:30

标签: javascript php jquery ajax

好吧,我有一个弹出窗口,显示有关客户的一些注释。内容(注释)通过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,但它不起作用。

请指引我正确的方向。

2 个答案:

答案 0 :(得分:0)

创建一个函数来调用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>

答案 1 :(得分:0)

您需要提供一个指向jQuery load()函数的URL,以告知您获取内容的位置。 所以要加载注释你可以试试这个:

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