这篇文章主要介绍了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() ?>相关推荐:
以上就是Yii2表单事件之Ajax提交实现方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号