3
我找不到Yii2以下方式提交數據:Yii2:如何驗證表單與AJAX,然後使用AJAX再次
- 首先驗證通過AJAX我的形式,因爲我有一個獨特的領域。
- 然後,如果驗證是正確的,通過AJAX將表單數據提交給表單操作。
這是我走到這一步:
筆者認爲:
<?php
$form = ActiveForm::begin([
'id' => 'subscribe-form',
'action' => ['site/subscribe'],
'validationUrl' => ['site/validate-subscribe'],
'validateOnSubmit' => true,
'enableAjaxValidation' => true,
]) ?>
<?= $form->field($model, 'name')->input('text', ['class' => 'w-input']) ?>
<?= $form->field($model, 'email')->input('text', ['class' => 'w-input']) ?>
<div class="form-group">
<?= Html::submitButton('SUSCRIBIRSE', ['class' => 'w-inline-block btn', 'name' => 'login-button']) ?>
</div>
<?php ActiveForm::end() ?>
在我的控制器:
public function actionValidateSubscribe(){
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
$model = new Subscription(Yii::$app->getRequest()->getBodyParams()['Subscription']);
if (!$model->validate()) {
return ActiveForm::validate($model);
}
}
}
public function actionSubscribe()
{
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
$model = new Subscription(Yii::$app->getRequest()->getBodyParams()['Subscription']);
if(!$model->validate()){
throw new NotAcceptableHttpException('Tiene errores de validación en la forma');
}
if($model->save()){
Yii::$app->mailer->compose('subscription', ['model'=>$model])
->setTo([$model->name => $model->email])
->setFrom(['Test' => '[email protected]'])
->setSubject('Por favor confirme su suscripción')
->send();
}
$response = [
'data'=>$model->getAttributes(),
'success'=>'true'
];
return $response;
}
}
在我的JS:
$(document).ready(function() {
$('body').on('beforeSubmit', 'form#subscribe-form', function() {
var form = $(this);
// return false if form still have some validation errors
if (form.find('.has-error').length) {
return false;
}
// submit form
$.ajax({
url : form.attr('action'),
type : 'post',
data : form.serialize(),
success: function (response) {
// do something with response
},
error : function() {
}
});
return false;
});
});
問題是,當我在ActiveForm中將「enableAjaxValidation」設置爲true時,yii.ActiveForm.js未觸發afterVAlidate或beforeSubmit事件。