微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Yii2实现ActiveForm ajax提交

做项目时总会碰到ajax提交的功能,特别是在做后台提交时,一般都会用模型自动生成,这个功能的使用会比较频繁,其实只要了解了流程,操作还是挺简单的,使用起来也方便。

表单部分

<?PHP $form = ActiveForm::begin([

‘action’ => [‘save’], //提交地址(*可省略*)

‘method’=>’post’, //提交方法(*可省略认POST*)

‘id’ => ‘form-save’, //设置ID属性

‘options’ => [

‘class‘ => ‘form-horizontal’, //设置class属性

],

‘enableAjaxValidation’ => true,

‘validationUrl’ => ‘validate-view’,

]); ?>

<?PHP echo $form->field($model,’company_name’, [‘inputoptions’ => [‘placeholder’=>’请输入商家名称’,’class‘ => ‘form-control’], ‘template’=>'<label for=“inputCompanyName” class=“col-sm-1 control-label”><span class=“text-red”>*</span> 商家名称</label><div class=“col-md-8”>{input}</div><label class=“col-sm-3” for=“inputError”>{error}</label>’])->textinput()?>

<?=Html::submitButton(‘保存’,[‘class‘=>’btn btn-primary’]); ?>

<?PHP ActiveForm::end(); ?>

其中:’enableAjaxValidation’ => true, 必须设置,告诉表单用ajax提交

控制器(controller)部分

控制器分两部分,一部分是效验表单的正确性,另外一部分是保存

一、效验部分

public function actionValidateView()

{

$model = new model();

$request = Yii::$app->getRequest();

if ($request->isPost && $model->load($request->post())) {

Yii::$app->response->format = Response::FORMAT_JSON;

return ActiveForm::validate($model);

}

}

二、保存部分

public function actionSave()

{

Yii::$app->response->format = Response::FORMAT_JSON;

$params = Yii::$app->request->post();

$model = $this->findModel($params[id]);

if (Yii::$app->request->isPost && $model->load($params)) {

return [‘success’ => $model->save()];

}

else{

return [‘code’=>’error’];

}

}

Ajax提交from表单

$(function(){

$(document).on(‘beforeSubmit’, ‘form#form-save’, function () {

var form = $(this);

//返回错误的表单信息

if (form.find(‘.has-error’).length)

{

return false;

}

//表单提交

$.ajax({

url : form.attr(‘action’),

type : ‘post’,

data : form.serialize(),

success: function (response){

if(response.success){

alert(‘保存成功’);

window.location.reload();

}

},

error : function (){

alert(‘系统错误’);

return false;

}

});

return false;

});

});

特别注意本人用的是Yii2 adminlte框架后台,具体操作过程视项目而定,基本操作过程都一样。

原文地址:https://www.toutiao.com/article/7119348324871848480/

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐