Yii2實現(xiàn)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)部分
控制器分兩部分,一部分是效驗表單的正確性,另外一部分是保存
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('系統(tǒng)錯誤'); return false; } }); return false; }); });
特別注意本人用的是Yii2 adminlte框架后臺,具體操作過程試項目而定,基本操作過程都一樣。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Zend Framework實現(xiàn)多文件上傳功能實例
這篇文章主要介紹了Zend Framework實現(xiàn)多文件上傳功能的方法,較為詳細的分析說明了Zend Framework實現(xiàn)多文件上傳的具體步驟與相關(guān)實現(xiàn)技巧,需要的朋友可以參考下2016-03-03thinkphp,onethink和thinkox中驗證碼不顯示的解決方法分析
這篇文章主要介紹了thinkphp,onethink和thinkox中驗證碼不顯示的解決方法,簡單分析了thinkPHP驗證碼不顯示的原因與相應的解決方法,具有一定參考借鑒價值,需要的朋友可以參考下2016-06-06Laravel事件系統(tǒng)實現(xiàn)瀏覽量的統(tǒng)計
Laravel的事件系統(tǒng)提供了一種簡單而強大的方式來實現(xiàn)瀏覽量的統(tǒng)計,通過創(chuàng)建瀏覽事件和事件監(jiān)聽器,以及在合適的地方觸發(fā)事件,我們可以輕松地實現(xiàn)網(wǎng)頁瀏覽量的統(tǒng)計功能,本文將介紹如何使用Laravel的事件系統(tǒng)來實現(xiàn)瀏覽量的統(tǒng)計2024-03-03