我正在尝试在我的网络项目上实现评论系统,我对 Yii 非常陌生。我希望用户能够提交评论,这反过来会更新数据库,并重新呈现所有帖子的评论(注意:我不希望整个页面刷新)。
我正在尝试使用 来实现这一点CHtml::ajaxSubmitButton
,但我似乎无法让它甚至拨打电话。我不知道如何检查是否正在拨打电话。
我目前的代码如下:
_questionComment
- 这部分呈现在“浏览”视图中
<div class="form">
<?php
$form = $this -> beginWidget('CActiveForm', array(
'id' => 'question-answer-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
));
$response = new QuestionAnswerForm;
?>
<div class="row">
<?php
echo $form->labelEx($response, 'link');
echo $form->textField($response, 'link');
echo $form->error($response, 'link');
?>
</div>
<div class="row">
<?php
echo $form->labelEx($response, 'description');
echo $form->textField($response, 'description');
echo $form->error($response, 'description');
?>
</div>
<div class="row buttons">
<?php echo CHtml::ajaxSubmitButton('Reply', 'comment', array(
'update'=>'#comments',
'type'=>'POST',
)); ?>
</div>
<?php $this->endWidget(); ?>
</div>
QuestionController/actionComment()
- 应该处理 ajax 请求
public function actionComment()
{
if(Yii::app()->request->isAjaxRequest)
{
//current user has posted a response
if(isset($_POST['QuestionAnswerForm']))
{
$response = new QuestionAnswerForm;
$response->attributes = $_POST['QuestionAnswerForm'];
//answer form has passed inspection
if($response->validate())
{
//save new answer to database
$newAnswer = new QuestionAnswer;
$newAnswer->link = $response->link;
$newAnswer->description = $response->description;
$newAnswer->question_id = Yii::app()->getRequest()->getQuery('id');
$newAnswer->user_id = Yii::app()->user->getId();
//adds a timestamp using a default timezone 'GMT'
$newAnswer->timestamp = Timestamp::getCurrentTimeStamp();
$newAnswer->save();
}
}
}
}
browse
- 这是呈现评论的地方。用户提交评论后,我希望浏览页面再次部分呈现所有评论。我尝试使用 ajaxSubmitButton 中的“更新”参数来实现这一点。
<?php
/*
* @var $this QuestionController
* @var $question Question
* @var $answers QuestionAnswer
*/
echo "<h1>" . $question['name'] . "</h1>";
echo "<h3>" . $question['description'] . "</h3>"
?>
<? $this->renderPartial('_renderComments', array('answers'=>$answers)); ?>
<? $this->renderPartial('_questionComment'); ?>