在 Yii 中通过 Ajax 提交表单.Yii正在双重提交表格


Submit a form via Ajax in Yii. Yii is double submitting the form

>我有以下内容:

我的观点

<?php $form = ActiveForm::begin(['id' => 'emailForm', 'action' => 'send-email', 'method' => 'post', 'enableAjaxValidation' => false, 'options' => ['class' => '']]) ?> 
<?= $form->field($emailModel, 'verifyCode')->widget(Captcha::className(), [
    'template' => '<div class="row"><div class="col-lg-3">{image}</div><div class="col-lg-6">{input}</div></div>',
]) ?>
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'email-button']) ?>

我的控制器

  public function actionSendEmail() {
    Yii::$app->response->format = Response::FORMAT_JSON;
    $model = new EmailModel();
    if ($model->load(Yii::$app->request->post()) && $model->validate()) {
      return ['info' => "Your message has been sent!"];
    } else {
      // error
      // return $model->errors;
      return ActiveForm::validate($model);
    }

我的模型

 public function rules()
    {
        return [
            [['name', 'from', 'to', 'message'], 'required'],
            [['from', 'to'], 'email'],
            ['verifyCode', 'captcha'],
        ];

JavaScript

jQuery(function() {
    $('#emailForm').submit(function(event) {
        event.preventDefault();
        $.post('send-email', $( "#emailForm" ).serialize(), function(data) {
            console.log (data);
//          $('#emailAlert').show().empty().append(data);
        });
        return false;
enter code here

event.preventDefault();return false;并没有阻止 Yii 自己提交表单,所以它是双重提交。

'enableAjaxValidation' => true导致 Yii 在每个字段的每次更改后验证表单,所以我将其设置为 false。

控制台投掷:

XHR finished loading: POST "http://localhost:81/shopping/send-email".send @ jquery.js
  Object {info: "Your message has been sent!"}
XHR finished loading: POST "http://localhost:81/shopping/send-email".send @ jquery.js
  Object {info: "Your message has been sent!"}

@ck_arjun有解决方案。我不得不将 JavaScript 更改为

$('#emailForm').on('beforeSubmit', function(event) {

我不得不使用.on()因为 JQuery 没有.beforeSubmit() http://api.jquery.com/category/events/form-events/。