当前位置: 移动技术网 > IT编程>开发语言>PHP > Yii2表单事件之Ajax提交实现方法

Yii2表单事件之Ajax提交实现方法

2017年12月12日  | 移动技术网IT编程  | 我要评论

七个侍寝夜结局,超正亚裔美女,河南省周口市

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

前言

yii2 现在使用 js 都必须要注册代码了。

要实现 ajax 提交,有两种方法。一是直接在 activeform 调用 beforesubmit 参数,但是个人认为这样没有很好的把 js 和 html 分开,所以我们这篇文章主要介绍第二种方法 - 外部写 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() ?>

更多关于yii相关内容感兴趣的读者可查看本站专题:《yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家基于yii框架的php程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网