这篇文章主要介绍了yii2表单事件之ajax提交实现方法,结合实例形式分析了yii2框架中ajax提交的具体实现技巧,需要的朋友可以参考下
本文实例讲述了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 gridview实现时间段筛选功能
yii 2.0自带的验证码使用经验分享
以上就是yii2表单事件之ajax提交实现方法的详细内容。