2013-12-19 40 views
1

這是顯示網站中前兩個註釋的HTML代碼。我想如果用戶點擊Load more comments按鈕,它應該加載通過jQuery AJAX返回的提取的評論,並將其附加到.comment_data div中的兩個divs,但它不工作,即使AJAX似乎正在返回預期結果。將jQuery AJAX響應附加到現有的DIV

這是HTML代碼:

<div class = 'feeds'> 
    <div class = 'comments'> 
    <div class = 'comment_data> 
    <div class = 'per_comment'> 
     <p> slideToggle!</p> 
    </div> 
    <div class = 'per_comment'> 
     <p> classToggle!</p> 
    </div> 
    <button class='morecomments' value='7' name = 'more' type='submit'> 
    Load more comments</button> 
    </div> 
</div> 
</div> 

這是AJAX代碼:

$(".morecomments").click(function() { 
var post_id = $(this).val(); 
var request = $.ajax({ 
    url: "comments.php", 
    type: "POST", 
    data: { post : post_id }, 
    dataType: "html" 
}); 
request.done(function(msg) { 
    $(this).prev('.per_comment').html(msg); 
}); 
}); 

而且comments.php了代碼:

if(isset($_POST['post'])) 
{ 
    $post_id = $_POST['post']; 
    $qry = "SELECT user_id, comment FROM comments WHERE post_id = ? ORDER BY time DESC LIMIT 1, 1000"; 
$q = $conn->prepare($qry) or die("ERROR: " . implode(":", $conn->errorInfo())); 
$q->bindParam(1, $post_id); 
$q->execute(); 
if($commentz = $q->fetchAll()){ 
foreach ($commentz as $comment){ 
    echo "<div class = 'per_comment'>"; 
     echo "<p>". $comment[0] ." ". $comment[1] . "</p>"; 
    echo "</div>"; 
    } 
    } 
    } 

回答

1

嘗試以下操作:

$(".morecomments").click(function() { 

    var $this = $(this);  

    var post_id = $(this).val(); 
    var request = $.ajax({ 
    url: "comments.php", 
    type: "POST", 
    data: { post : post_id }, 
    dataType: "html" 
    }); 
request.done(function(msg) { 
    $this.prev('.per_comment').html(msg); 
    }); 

});

+0

像魅力,它的工作!謝謝一堆。 – Yax

1

this是不是你認爲它是。嘗試設置ajax選項的context屬性:

$(".morecomments").click(function() { 
    var post_id = $(this).val(); 
    var request = $.ajax({ 
     url: "comments.php", 
     type: "POST", 
     data: { 
      post: post_id 
     }, 
     dataType: "html", 
     context: this 
    }); 
    request.done(function (msg) { 
     $(this).prev('.per_comment').html(msg); 
    }); 
}); 
+0

像魅力一樣,這也工作!謝謝。 – Yax