我达到了这个状态:我做了一张桌子 - >
| likes |
| like_id(primary key) | user_id(foreign key) | comment_id(foreign key) |
点击链接时,我的代码应该在likes
表中添加一行
并刷新持有的<div id="like_"<?php $comment['comment_id'] ?>>
喜欢数。这应该通过ajax发生。我不熟悉AJAX所以请给我建议。我正确的方式吗?
我的行动反馈:
public function actionFeedback($comment_id)
{
if(\Yii::$app->request->isAjax)
{
$user_id = \Yii::$app->user->identity->id;
\Yii::$app->db->createCommand("INSERT INTO likes(user_id, comment_id)
VALUES ($user_id, $comment_id)")->execute();
$likes = \Yii::$app->db->createCommand("SELECT COUNT(*)
FROM likes
WHERE comment_id=$comment_id")->queryScalar();
return $likes;
}
}
和我的观点comments.php:
<?php
use yii\helpers\Html;
use app\models\BlogUser;
use app\controllers\PostController;
?>
<div class="container">
<div class="row">
<div class="col-md-12">
<?php foreach ($comments as $comment): ?>
<div class='col-md-3 post-prof-img'>
<?php
$currUser = BlogUser::find()->where(['id' => $comment['author_id']])->one();
$commentID = $comment['comment_id'];
$likes = \Yii::$app->db->createCommand("SELECT COUNT(*)
FROM likes
WHERE comment_id=$commentID")->queryScalar();
?>
<?= Html::img('../images/' . $currUser->image, ['class' => 'tall img-circle']) ?>
<p class="text-center title-par">
<em><strong><?= $currUser->username ?></strong></em>
</p>
</div>
<div class='col-md-9 col-md-offset-1'>
<div class='post-comment'>
<p><em><?= $comment['comment_content'] ?></em></p>
</div>
<div class='comment-options'>
<div class='col-md-8'>
<?php
if(\Yii::$app->user->identity->id == $comment['author_id'] || PostController::isAdmin())
{
echo Html::a('Edit',['update-comment', 'id' => $comment['comment_id']]);
echo Html::a('Delete',
['delete-comment', 'id' => $comment['comment_id']],
['data' => [
'confirm' => 'Are you sure?',
'method' => 'POST'
]
]);
}
echo Html::a('Like',[''],['class' => 'like_up', 'data_id' => $comment['comment_id']]);
echo Html::a('Dislike');
?>
</div>
<div class='col-md-4 text-right'>
<div class="ajax-helper">
<span class='glyphicon glyphicon-hand-up' style="color:green"></span>
<span id="likes-"<?php $comment['comment_id'] ?>><?= $likes ?></span>
<span class='glyphicon glyphicon-hand-down' style="color:red"></span>
</div>
</div>
</div>
</div>
<?php endforeach; ?>
<?php
$this->registerJs("
$('.like_up').on('click', function(event){
event.preventDefault();
var id = $(this).attr('data_id');
$.ajax({
url : '".\yii\helpers\Url::to(['feedback'])."?id='+id,
cache : false,
success : function( data ){
$('#likes-'+id).html( data );
}
});
});
");
?>
<div>
<?= Html::a('Add Comment', ['create-comment', 'id' => $_GET['id']],['class' => 'btn btn-primary add-comment', 'style'=>'margin-top: 2%']) ?>
</div>
</div>
</div>
</div>
使用这行代码我收到错误:
GET http://letsblog/post/feedback?id=25&_=1491990823748 400 (Bad Request)
从我在谷歌上找到的问题是在我的ajax部分,但不知道如何解决它:/
提前谢谢!
答案 0 :(得分:0)
url : '".\yii\helpers\Url::to(['feedback'])."?comment_id='+id,
将url替换为这样的ajax请求部分。