查看文件:
<?php use yii; use yii\bootstrap\ActiveForm; use yii\helpers\Html; ?> <?php $form = ActiveForm::begin([ 'action' => ['comments/ajax-comment'], 'options' => [ 'class' => 'comment-form' ] ]); ?> <?= $form->field($model, 'comment'); ?> <?= Html::submitButton("Submit", ['class' => "btn"]); ?> <?php ActiveForm::end(); ?>Javascript:
jQuery(document).ready(function($) { $(".comment-form").submit(function(event) { event.preventDefault(); // 停止提交 var data = $(this).serializeArray(); var url = $(this).attr('action'); $.ajax({ url: url, type: 'post', dataType: 'json', data: data }) .done(function(response) { if (response.data.success == true) { alert("Wow you commented"); } }) .fail(function() { console.log("error"); }); }); });控制器操作:
public function actionAjaxComment() { $model = new Comments(); if (Yii::$app->request->isAjax) { Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; if ($model->load(Yii::$app->request->post()) && $model->save()) { return [ 'data' => [ 'success' => true, 'model' => $model, 'message' => 'Model has been saved.', ], 'code' => 0, ]; } else { return [ 'data' => [ 'success' => false, 'model' => null, 'message' => 'An error occured.', ], 'code' => 1, // 您自己了解的一些语义代码 ]; } } }