Yii ajax表单提交和更新?

时间:2013-09-07 03:45:57

标签: php jquery yii yii-components

我正在尝试在我的网络项目上实施评论系统,我对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中的'update'参数来实现这一点。

<?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'); ?>

1 个答案:

答案 0 :(得分:3)