在yii2中插入而不刷新

时间:2016-06-30 21:58:50

标签: javascript php yii

我正在使用yii2开发一个Web应用程序.i做了一个竖起拇指和拇指按下按钮。它只是插入用户以及用户选择上/下表的内容。但我不认为我会以正确的方式解决这个问题,因为在用户点击或关闭之后它会刷新。我希望它插入而不刷新。

这是视图

       <?php $form = ActiveForm::begin(['id' => "contact-form",
            'enableClientValidation' => false,
            ]); 
          ?>
     <input type="hidden"  class="form-control"  value="up" required="true" name="Thumbs[rate]" id="topic" placeholder="topic">
     <?= Html::submitButton('Save', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>   
     <button type="submit" id="save" name="save">enter</button>  
     <?php ActiveForm::end(); ?>   

                 <?php $form = ActiveForm::begin(['id' => "contact-form",
        'enableClientValidation' => false,
        ]); 
      ?>
 <input  type="hidden" class="form-control" hidden="true" value="down" required="true" name="Thumbs[rate]" id="topic" placeholder="topic">
 <?= Html::submitButton('Save', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?> 
     <?php ActiveForm::end(); ?>   

如果你注意到我似乎在类型为hidden的输入中保持up和down的值。只是想知道更好的方法。

这是我的控制器功能

 public function actionBlog()
    { 
     $thumbs= new Thumbs(); 
       $thumbs->user=Yii::$app->user->identity->email;
          $thumbs->topic_id = '1';

        if ($thumbs->load(Yii::$app->request->post()) && $thumbs->validate()) {
        $thumbs->load($_POST);

         $thumbs->save();
          return $this->refresh();
     }

         return $this->render('blog');

    }  

我也尝试使用ajax,但似乎效果不佳

1 个答案:

答案 0 :(得分:0)

您可以使用Pjax

这是一个简单的示例,您应该能够应用于您的问题。为了清楚起见,我已经包含了一些注释,但我会建议您查看this tutorial以获取更多信息和一些扩展示例。

查看(vote.php):

<?php
use yii\widgets\Pjax;
use yii\helpers\Html;
use common\models\Thumbs;
?>

<?php Pjax::begin(['enablePushState' => false]); ?>
<?= Html::a('', ['site/upvote'], ['class' => 'btn btn-lg btn-warning glyphicon glyphicon-arrow-up']) ?>
<?= Html::a('', ['site/downvote'], ['class' => 'btn btn-lg btn-primary glyphicon glyphicon-arrow-down']) ?>
<h1><?= Thumbs::find()->where(['=', 'post_id', '1'])->one()->votes ?></h1>
<?php Pjax::end(); ?>

SiteController:

public function actionVote()
{
    return $this->render('vote');
}

public function actionUpvote()
{
    // find the thumbs record for the related post
    $thumbsRecord = Thumbs::find()->where(['=', 'post_id', '1'])->one();

    // increment the thumbs count
    $thumbsRecord->votes += 1;

    // ensure change persists to db
    $thumbsRecord->save();

    // return value to the view
    return $this->render('vote', [
        'votes' => $thumbsRecord->votes,
    ]);
}

/**
 * Similar functionality to actionUpvote
 */
public function actionDownvote()
{
    $thumbsRecord = Thumbs::find()->where(['=', 'post_id', '1'])->one();
    $thumbsRecord->votes -= 1;
    $thumbsRecord->save();
    return $this->render('vote', [
        'votes' => $thumbsRecord->votes,
    ]);
}

该模型只是一个包含以下字段的表:

  • id(int,primary key)
  • post_id(int)
  • votes(int,default 0)