Jquery ajax评论帖两次

时间:2015-08-24 14:25:08

标签: php jquery ajax

我正在开发一个简单的ajax帖子和评论系统。问题是,当我在页面上发几个帖子并尝试对它们发表评论时,每个评论都会进行两次。看看这个pic

这是我的表格:

<h4>Simple ajax post and comment</h4>
    <form action="" class="post-form">
        <textarea placeholder="type something" name="post_body" id="" class="post"></textarea>
        <input type="submit" value="Post" class="submit">
    </form>
    <div class="result"></div>

这是ajax部分:

$( document ).ready(function() {

        //Submitting main post form
       $(".post-form").submit(function(e) {
            e.preventDefault();

            var dataHolder = '';

            //Sending main post
            $.ajax({
              type: "POST",
              url: 'server.php',
              data: $(this).serialize(),
              success: function(data){
                dataHolder += data;
                runOnComplete();
              },
            });

            //callback function on ajax success
            function runOnComplete() {
                $('.post').val('');
                data = dataHolder;
                var html = '<div class="main-message">' + 'Post: ' + data + '</div><div class="reply"><form action="" class="form-reply"><textarea placeholder="Comment" class="reply-bx" name="reply"></textarea><input type="submit" class="reply-btn" value="comment"></div>';
                $(".result").prepend(html);

                //posting reply
                $('.form-reply').submit(function(e) {
                    e.preventDefault();

                    var ctx = $(this);
                    $.ajax({
                      type: "POST",
                      url: 'server2.php',
                      data: $(this).serialize(),
                      success: function(data){
                        $('.reply-bx').val('');
                        var h = '<p>' + data + '</p>';
                        ctx.append(h);
                      },
                    });
                });

            }

        });
    });

Php文件很简单。

server.php:

$post = $_POST['post_body'];
echo $post;

server2.php:

$comment = $_POST['reply'];
echo $comment;

您可以从此处直接测试: Ajax post and comment system。发几个帖子并对它们发表评论。看评论是两次。

如果您需要查看整个页面,请查看此处。 jsFiddle。但是我注意到,ajax请求在这里不起作用。

如何解决?每条评论只应该一次。

1 个答案:

答案 0 :(得分:0)

https://jsfiddle.net/gb2tpr4h/3/尝试将其放在runOnComplete函数之外,在其他表单旁边单击函数

PATCH

RunOnComplete必须是这样的:

 //posting reply
            $('.form-reply').submit(function(e) {
                e.preventDefault();

                var ctx = $(this);
                $.ajax({
                  type: "POST",
                  url: 'server2.php',
                  data: $(this).serialize(),
                  success: function(data){
                    $('.reply-bx').val('');
                    var h = '<p>' + data + '</p>';
                    ctx.append(h);
                  },
                });
            });

在各种评论后编辑: https://jsfiddle.net/gb2tpr4h/3/ 有效。问题是,有两个帖子你有两个.reply在哪里放置评论和拖曳表格......