欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Yii2表單事件之Ajax提交實(shí)現(xiàn)方法

 更新時(shí)間:2017年05月04日 10:27:35   作者:yhdsir  
這篇文章主要介紹了Yii2表單事件之Ajax提交實(shí)現(xiàn)方法,結(jié)合實(shí)例形式分析了Yii2框架中ajax提交的具體實(shí)現(xiàn)技巧,需要的朋友可以參考下

本文實(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),所以我們這篇文章主要介紹第二種方法 - 外部寫 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,你還可以這樣寫:

<?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)容感興趣的讀者可查看本站專題:《Yii框架入門及常用技巧總結(jié)》、《php優(yōu)秀開(kāi)發(fā)框架總結(jié)》、《smarty模板入門基礎(chǔ)教程》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫(kù)操作入門教程》及《php常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總

希望本文所述對(duì)大家基于Yii框架的PHP程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論