Yii2 form event Ajax submission implementation method

不言
Release: 2023-03-25 10:02:02
Original
1614 people have browsed it

这篇文章主要介绍了Yii2表单事件之Ajax提交实现方法,结合实例形式分析了Yii2框架中ajax提交的具体实现技巧,需要的朋友可以参考下

本文实例讲述了Yii2表单事件之Ajax提交实现方法。分享给大家供大家参考,具体如下:

前言

Yii2 现在使用 JS 都必须要注册代码了。

要实现 Ajax 提交,有两种方法。一是直接在 ActiveForm 调用 beforeSubmit 参数,但是个人认为这样没有很好的把 JS 和 HTML 分开,所以我们这篇文章主要介绍第二种方法 - 外部写 JS 方法。

表单部分

<?php $form = ActiveForm::begin([
  &#39;id&#39;   => $model->formName(),
  &#39;action&#39; => [&#39;/apitools/default/index&#39;]
]); ?>
Copy after login

Ajax

<?php
$js = <<<JS
// get the form id and set the event
$(&#39;form#{$model->formName()}&#39;).on(&#39;beforeSubmit&#39;, function(e) {
  var \$form = $(this);
  // do whatever here, see the parameter \$form? is a jQuery Element to your form
}).on(&#39;submit&#39;, function(e){
  e.preventDefault();
});
JS;
$this->registerJs($js);
Copy after login

如果你使用了 JsBlock,你还可以这样写:

<?php JsBlock::begin() ?>
  <script>
    $(function () {
      jQuery(&#39;form#apitool&#39;).on(&#39;beforeSubmit&#39;, function (e) {
        var $form = $(this);
        $.ajax({
          url: $form.attr(&#39;action&#39;),
          type: &#39;post&#39;,
          data: $form.serialize(),
          success: function (data) {
            // do something
          }
        });
      }).on(&#39;submit&#39;, function (e) {
        e.preventDefault();
      });
  </script>
<?php JsBlock::end() ?>
Copy after login

相关推荐:

yii gridview实现时间段筛选功能

Yii 2.0自带的验证码使用经验分享


The above is the detailed content of Yii2 form event Ajax submission implementation method. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!