这篇文章主要 为大家详细介绍了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><p class="col-md-8">{input}</p><label class="col-sm-3" for="inputError">{error}</label>'])->textInput()?> <?=Html::submitButton('保存',['class'=>'btn btn-primary']); ?> <?php ActiveForm::end(); ?>
其中:'enableAjaxValidation' => true, 必须设置,告诉表单用ajax提交
控制器(controller)部分
控制器分两部分,一部分是效验表单的正确性,另外一部分是保存
1、效验部分
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); } }
2、保存部分
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框架后台,具体操作过程试项目而定,基本操作过程都一样。
相关推荐:
以上是Yii2实现ActiveForm ajax提交的详细内容。更多信息请关注PHP中文网其他相关文章!

DependencyInjection(DI)inPHPenhancescodeflexibilityandtestabilitybydecouplingdependencycreationfromusage.ToimplementDIeffectively:1)UseDIcontainersjudiciouslytoavoidover-engineering.2)Avoidconstructoroverloadbylimitingdependenciestothreeorfour.3)Adhe

到Improveyourphpwebsite的实力,UsEthestertate:1)emplastOpCodeCachingWithOpcachetCachetOspeedUpScriptInterpretation.2)优化的atabasequesquesquesquelies berselectingOnlynlynnellynnessaryfields.3)usecachingsystemssslikeremememememcachedisemcachedtoredtoredtoredsatabaseloadch.4)

是的,itispossibletosendMassemailswithp.1)uselibrarieslikeLikePhpMailerorSwiftMailerForeffitedEmailSending.2)enasledeLaysBetemailStoavoidSpamflagssspamflags.3)sylectynamicContentToimpovereveragement.4)

DependencyInjection(DI)inPHPisadesignpatternthatachievesInversionofControl(IoC)byallowingdependenciestobeinjectedintoclasses,enhancingmodularity,testability,andflexibility.DIdecouplesclassesfromspecificimplementations,makingcodemoremanageableandadapt

使用PHP发送电子邮件的最佳方法包括:1.使用PHP的mail()函数进行基本发送;2.使用PHPMailer库发送更复杂的HTML邮件;3.使用SendGrid等事务性邮件服务提高可靠性和分析能力。通过这些方法,可以确保邮件不仅到达收件箱,还能吸引收件人。

计算PHP多维数组的元素总数可以使用递归或迭代方法。1.递归方法通过遍历数组并递归处理嵌套数组来计数。2.迭代方法使用栈来模拟递归,避免深度问题。3.array_walk_recursive函数也能实现,但需手动计数。

在PHP中,do-while循环的特点是保证循环体至少执行一次,然后再根据条件决定是否继续循环。1)它在条件检查之前执行循环体,适合需要确保操作至少执行一次的场景,如用户输入验证和菜单系统。2)然而,do-while循环的语法可能导致新手困惑,且可能增加不必要的性能开销。

在PHP中高效地哈希字符串可以使用以下方法:1.使用md5函数进行快速哈希,但不适合密码存储。2.使用sha256函数提高安全性。3.使用password_hash函数处理密码,提供最高安全性和便捷性。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

WebStorm Mac版
好用的JavaScript开发工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

SublimeText3汉化版
中文版,非常好用

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)