我们就yii2 ActiveForm如何以Ajax的方式提交表单做一个简单的说明,这也是我们今天主题的重点。
yii2中,ActiveForm默认做了客户端验证,但是表单的提交,却不是无刷新的。也就是常常看到的表单提交后页面会刷新。如果想要开启无刷新的模式,只需要在ActiveForm开始开启enableAjaxValidation即可,像下面这样
<?php $form = ActiveForm::begin([ 'id' => 'form-id', 'enableAjaxValidation' => true, ] ); ?>
注意哦,id和enableAjaxValidation一个都不能少。
接着看服务端的实现
if ($model->load(Yii::$app->request->post())) {
Yii::$app->response->format = yiiwebResponse::FORMAT_JSON;
if ($errors = yiiwidgetsActiveForm::validate($model)) {
return $errors;
} else {
if($model->save(false)) {
return $this->redirect(['index']);
}
}
}
return $this->render('create', [
'model' => $model,
]);如此一来就简单的实现了yii2异步无刷新提交表单了!
其实下面说与不说已经不重要了,主要是写给一些懒人参考吧。聪明的人看了标题就应该明白了如何解决modal通过ActiveForm提交表单的问题。
为了兼容modal,注意我们说的是兼容而不是实现,我们对程序稍稍做了些改动,仅做参考。
if ($model->load(Yii::$app->request->post())) {
if ($model->save()) {
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = yiiwebResponse::FORMAT_JSON;
return ['success' => true];
}
return $this->redirect(['index']);
} else {
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = yiiwebResponse::FORMAT_JSON;
return yiiwidgetsActiveForm::validate($model);
}
}
}
if (Yii::$app->request->isAjax) {
return $this->renderAjax('create', [
'model' => $model,
]);
} else {
return $this->render('create', [
'model' => $model,
]);
}| 欢迎光临 一起源码网 (https://www.171739.xyz/) | Powered by Discuz! X3.3 |