本文实例讲述了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程序设计有所帮助。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!