将jQuery AJAX响应附加到现有DIV

时间:2013-12-19 23:43:22

标签: php jquery html ajax

这是显示我网站上前两条评论的HTML代码。我想如果用户点击Load more comments按钮,它应该加载通过jQuery AJAX返回的获取的注释,并将其附加到divs div中的两个.comment_data但是它不是即使AJAX似乎正在返回预期的结果。

这是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>";
    }
    }
  }

2 个答案:

答案 0 :(得分: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 ); 
  });

});

答案 1 :(得分: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);
    });
});