javascript - AJAX 内的 AJAX 无法正常工作

标签 javascript php jquery ajax

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

这只是一个关于它如何运作的小故事。我希望每当发表评论时,它都应该附加到现有评论中并立即通过 Ajax 。它执行此操作,但它会重新显示每个评论 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('');
        });
    });
})

提前,谢谢。

最佳答案

在 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
    });
});

关于javascript - AJAX 内的 AJAX 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20736591/

相关文章:

javascript - jpg 转 base64 javascript

javascript - 将 highcharts 数据导出到 CSV 文件

JavaScript 函数禁用整个 JS 代码

php - 在将 Twitter 状态输出到网页之前,是否需要对其进行格式化?

php - URL 路由器中的组和中间件

php - 无法使用javascript访问json文件

javascript - 如果是移动设备则更改背景图片

jquery - 如何将css应用于jquery中具有相同前缀的多个控件

jquery - 仅为嵌套模态显示模态背景

javascript - 如何使用 jQuery Ajax 指定正确的输入以提交多个表单(可变数字)