这是显示我网站上前两条评论的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>";
}
}
}
答案 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);
});
});