【问题标题】:AJAX within AJAX not working correctlyAJAX 中的 AJAX 无法正常工作
【发布时间】:2014-01-11 06:17:02
【问题描述】:

我在社交网站上工作。在第一次加载时,它会获取所有帖子,每个帖子最多有两个评论。如果 cmets 超过两个 它将More comment按钮附加到它,如果单击,它将显示所有cmets并将按钮替换为Less comment

这只是它如何工作的一个小故事。我希望无论何时发表评论,它都应该附加到现有评论中并通过立即显示 阿贾克斯。它会这样做,但它会重新显示每个 cmets 3 次,当您重新加载页面时,一切正常...

<div class = 'post_updates'>
  <div class = 'feeds'>
    <div class = 'commentdiv'>
       <textarea autocomplete = 'off' class='commenttext form-control' rows = '1'
       placeholder='Have your say...'></textarea>
       <button class='comment btn btn-xs btn-primary onespacedown' value = '7'
        type='submit'>Comment</button>
    </div>
  </div>
</div>

jQuery AJAX 代码:

 $('.feeds').on('click', '.comment', function () {
var $this = $(this);
var post_comment = $this.parents('.feeds').find('.commenttext').val();
var post_id = $(this).val();
var user_id = $(".user_id").text();
var request = $.ajax({
      url: "insert.php",
      type: "POST",
      data: { post : post_id , user : user_id, comment: post_comment },
      dataType: "html"
    });
    request.done(function( msg ) {    
        $pc = $this.parents('.feeds').find('.per_comment');
        //fetch comments and display
            var request = $.ajax({
                url: "comments.php",
                type: "POST",
                data: {
                    post: post_id,
                    user: user_id
                },
                dataType: "html"
            });
            request.done(function (msg) {
                $pc.html(msg).data('loaded', true);
                $this.replaceWith("<button class='lesscomments btn-block pullcomments' value='' name = 'more' type='submit'>Less comments</button>"); 
                $this.parents('.feeds').find('.commenttext').val('');
        });
    });
})

提前,谢谢。

【问题讨论】:

标签: javascript php jquery ajax


【解决方案1】:

在 jquery 中尝试 $.post

$.post("insert.php",{post : post_id , user : user_id, comment: post_comment},function(){})
.success(function(data){
    //callback when first post completed
    //begin second ajax post
    $.post("comments.php",{post: post_id,user: user_id},function(){})
    .success(function(){
        //call back when second post completed
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-13
    • 2014-07-23
    相关资源
    最近更新 更多