如何在不重新加载整个页面的情况下将表单提交到同一页面并刷新内容


How to submit a form to the same page and refresh content without reloading entire page

基本上,我想做的是在不刷新整个页面的情况下向页面发布评论。只是评论DIV,所以它看起来像是发布和刷新顺利。

表单提交到它所在的页面。我发现的所有内容都向我展示了如何使用间隔不断刷新内容。我只想在有人发布评论时刷新评论DIV。

我找不到正确的ajax代码来按照我想要的方式执行此操作。

这是我的代码:

var submit_button = $('#submit_button');
submit_button.click(function() {
    var commentSubmitted= $('commentSubmitted').val();

    var update_div = $('#update_div');
    $.ajax({
        type: 'POST',
        url: '/blog/',
        data: data,   
        success:function(html){
           update_div.html(html);
        }
    });
});

在同一个PHP文件中,我有到DB:的帖子

if($_POST[commentSubmitted])
{
  $query="INSERT INTO comments (commentSubmitted) VALUES ('$commentSubmitted')";
  mysql_query($query);
}

HTML用于表单:

<form id="flow" method='post' action='/blog/'>
<textarea name='commentSubmitted' ></textarea>
<input type='submit' value='Post'/>

包含所有注释的DIV看起来是这样的:

<DIV id='AllComments'>
// comments displayed here
</DIV>

因此,在提交表单后,我希望重新加载"AllComments"DIV。

最好使用jQuery对服务器进行ajax调用并检索所需的数据。

检索数据有两种方法。检索要在json数组中显示的附加注释并使用javascript进行处理,或者在服务器端创建html并在注释部分中附加/替换html。

使用Json

$.ajax({
  url: "the_ajax_url_here",
  type: "post",
  data: {paramTitle: "paramValue", paramTitle1: "paramValue1"},
  dataType: "json"
  success: function(response) {
    // handle the response
  }
});

检索Html

$.ajax({
  url: "the_ajax_url_here",
  type: "post",
  data: {paramTitle: "paramValue", paramTitle1: "paramValue1"},
  dataType: "html"
  success: function(response) {
    // set the html of comments section to the newly retrieved html
    $("comments_section_selector").html(response);
  }
});

我要做的是在json数组中检索新添加的注释,然后使用javascript将其附加到注释部分。

编辑:看到你的代码后,我有一些评论可能会对你有所帮助。我个人更喜欢在单独的文件中处理ajax请求的代码。在该文件中,您可以存储新的注释并创建html来显示该注释。然后在成功函数中,只需将新的html附加到注释部分,如下所示:

success: function(response) {
  $('#AllComments').append(response);
}

您也可以使用预端在顶部显示新的评论

$('#AllComments').prepend(response);

很简单,希望你能做到

submit_button.click(function() {
    var commentSubmitted= $('commentSubmitted').val();

    var update_div = $('#update_div');
    $.ajax({
        type: 'POST',
        url: '/blog/',
        data: data,   
        success:function(html){
           update_div.html(html);
        }
    });
});

然后你去插入数据

if($_POST[commentSubmitted])
{
  $query="INSERT INTO comments (commentSubmitted) VALUES ('$commentSubmitted')";
  mysql_query($query);
  //After Inserting data retrieve back all the comments from db
  $sql = "select * from comments";//any query and execute it
  $query = mysql_query($sql);
  while($data = mysql_fetch_array($query)){
  echo $data["comments"];//Echo your commenets here
  }
  exit;
}

这就是