首页 > PHP教程 > php开发知识文章

Yii2 表单事件之Ajax提交的实现

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

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

要实现 Ajax 提交,有两种方法。一是直接在 ActiveForm 调用 beforeSubmit 参数,二是外部写 JS 方法。

php表单部分

<?php
$form = ActiveForm::begin(
[
'id' => $model->formName(),
'action' => ['/apitools/default/index']
]
);

?>

js部分

<?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框架的PHP程序设计有所帮助。

关闭
感谢您的支持,我会继续努力!
扫码打赏,建议金额1-10元


提醒:打赏金额将直接进入对方账号,无法退款,请您谨慎操作。