CActiveForm 和 ajaxSubmitButton 不工作

CActiveForm and ajaxSubmitButton not working

这是我的代码:

    <?php
    $form = $this->beginWidget('CActiveForm', array(
        'id' => 'swim-subscribe-form',
        'enableAjaxValidation' => true,
        'action'=>"/mycontroller/myfunction"
            ));
    ?>
    <?php 
          echo CHtml::ajaxSubmitButton('Save',array('/mycontroller/myfunction'),array(
         'type'=>'POST',
         'dataType'=>'post',
         'success'=>'js:function(data){
          }',
          ));
     $this->endWidget();
     ?>

这是我的控制器:

public actionMyFunction(){
        $model = new MyModel;
        $this->performAjaxValidation($model);
        if ($model->save()) {
          $this->redirect('/another_controller');
        }
}
protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'swim-subscriber-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

这段代码不知何故,它总是提交我的 url /mycontroller/myfunction。它没有在我的控制台上显示我通过 ajax 调用 /mycontroller/myfunction。为什么?

UPDATE 这就是生成我的 ajaxSubmitButton:

<input name="yt0" value="Save" id="yt0" type="submit">

这样可以吗?

您的代码中有错字。在视图文件中,表单的 ID 是
'id' => 'swim-subscribe-form',

但在 ajax 验证期间,您正在检查 id
$_POST['ajax'] === 'swim-subscriber-form' // there is an extra R at the end of "subscriber"

因此 ajax 验证永远不会运行,yii 应用程序永远不会结束,它始终被视为提交。

要么修复您的表单 ID-s,要么从控制器中的 ajax 验证中删除 ID 检查:

if (isset($_POST['ajax']) && $_POST['ajax'] === 'swim-subscribe-form') { // this has to match with the form ID
    echo CActiveForm::validate($model);
    Yii::app()->end();
}

if(Yii::app()->getRequest()->getIsAjaxRequest()) {
    echo CActiveForm::validate($model);
    Yii::app()->end();
}

如果您在一个页面上有多个表单(具有相同的操作),并且您不想 ajax 验证每个表单,或者如果 ajax 验证干扰其他 ajax 对同一操作的请求。我很少在 ajax 验证期间检查表单 ID。