本文實(shí)例講述了Yii2表單事件之Ajax提交實(shí)現(xiàn)方法。分享給大家供大家參考,具體如下:
前言
Yii2 現(xiàn)在使用 JS 都必須要注冊(cè)代碼了。
要實(shí)現(xiàn) Ajax 提交,有兩種方法。一是直接在 ActiveForm 調(diào)用 beforeSubmit 參數(shù),但是個(gè)人認(rèn)為這樣沒(méi)有很好的把 JS 和 HTML 分開(kāi),所以我們這篇文章主要介紹第二種方法 - 外部寫(xiě) JS 方法。
表單部分
<?php $form = ActiveForm::begin([ 'id' => $model->formName(), 'action' => ['/apitools/default/index'] ]); ?>
Ajax
<?php $js = <<<JS // get the form id and set the event $('form#{$model->formName()}').on('beforeSubmit', function(e) { var \$form = $(this); // do whatever here, see the parameter \$form? is a jQuery Element to your form }).on('submit', function(e){ e.preventDefault(); }); JS; $this->registerJs($js);
如果你使用了 JsBlock,你還可以這樣寫(xiě):
<?php JsBlock::begin() ?> <script> $(function () { jQuery('form#apitool').on('beforeSubmit', function (e) { var $form = $(this); $.ajax({ url: $form.attr('action'), type: 'post', data: $form.serialize(), success: function (data) { // do something } }); }).on('submit', function (e) { e.preventDefault(); }); </script> <?php JsBlock::end() ?>
更多關(guān)于Yii相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《Yii框架入門(mén)及常用技巧總結(jié)》、《php優(yōu)秀開(kāi)發(fā)框架總結(jié)》、《smarty模板入門(mén)基礎(chǔ)教程》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門(mén)教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫(kù)操作入門(mén)教程》及《php常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家基于Yii框架的PHP程序設(shè)計(jì)有所幫助。
【網(wǎng)站聲明】本站除付費(fèi)源碼經(jīng)過(guò)測(cè)試外,其他素材未做測(cè)試,不保證完整性,網(wǎng)站上部分源碼僅限學(xué)習(xí)交流,請(qǐng)勿用于商業(yè)用途。如損害你的權(quán)益請(qǐng)聯(lián)系客服QQ:2655101040 給予處理,謝謝支持。