2013-12-23 88 views
1

我在社交網站上工作。在第一次加載時,它會提取所有帖子,每個帖子都有兩個註釋最大值。如果評論超過兩個 它附加More comment按鈕,如果點擊,它會顯示所有評論,並用Less comment替換按鈕。AJAX內的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中

+0

@Tats_innit:jQuery.ajax處理繼續迴應:「成功:」 VS「.done」(http://stackoverflow.com/q/8840257/1438393) –

+0

@Tats_innit'success'與'done'完全相同... – Yax

+0

Agreed @AmalMurali我錯過了第二個電話:http://stackoverflow.com/questions/8847829/what-is-difference-between-success - 完成方法的AJAX –

回答

0

試$。員額

$.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 
    }); 
}); 
+0

上面的代碼有什麼區別? – Yax