前言
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/
