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() ?>

參考:http://www.ramirezcobos.com/2014/09/12/how-to-implement-form-events-on-yii2/

來源地址:http://www.getyii.com/topic/13


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM