本文介绍了CActiveForm 和 ajaxSubmitButton 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

    <?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.为什么?

This code somehow, it always do a submit my url /mycontroller/myfunction. It doesn't show on my console that I call the /mycontroller/myfunction through ajax. Why ?

UPDATE 这就是生成我的 ajaxSubmitButton 的原因:

UPDATE This is what generated my ajaxSubmitButton:

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

这样好吗?

推荐答案

您的代码中存在拼写错误.在视图文件中,表单的 ID 是
'id' =>'游泳订阅表单',

You have a typo in your code. In the view file the ID of the form is
'id' => 'swim-subscribe-form',

但是在 ajax 验证期间,您正在检查 id
$_POST['ajax'] === 'swim-subscriber-form'//"subscriber" 后面多了一个R

But during ajax validation you are checking for the id
$_POST['ajax'] === 'swim-subscriber-form' // there is an extra R at the end of "subscriber"

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

Therefore the ajax validation never runs, the yii app never ends, and it is always considered as a submit.

修复您的表单 ID,或者从控制器中的 ajax 验证中删除 ID 检查:

Either fix your form ID-s, or remove the ID check from the ajax validation in the controller:

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 请求,则表单 ID 检查非常有用.我很少在 ajax 验证过程中检查表单 ID.

The form ID check is useful if you have multiple forms on a page (with same action), and you don't want to ajax validate each of them or if the ajax validation interferes with other ajax request to the same action. I rarely check for the form ID during ajax validation.

这篇关于CActiveForm 和 ajaxSubmitButton 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 07:50