【问题标题】:Yii2. How to avoid "incorrect code" while using Captcha + Ajax?Yii2.使用 Captcha + Ajax 时如何避免“错误代码”?
【发布时间】:2020-06-22 22:48:18
【问题描述】:

我正在尝试解决这个大问题,但找不到漂亮而简单的解决方案。 启用 ajax 验证后,验证码无法正常工作。 总是出现“验证码不正确”。

view.php:

<?php $form = ActiveForm::begin([
            'id' => 'form-signup',
            'enableAjaxValidation' => true,
        ]); ?>

行动:

public function actionSignup()
{
    $model = new SignupForm();

    if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {

        Yii::$app->response->format = Response::FORMAT_JSON;
        return ActiveForm::validate($model);
    }

    if($model->load(Yii::$app->request->post())) {

        if ($user = $model->signup()) {

            if (Yii::$app->getUser()->login($user)) {
                return $this->goHome();
            }
        }
    }

【问题讨论】:

    标签: ajax yii2 captcha


    【解决方案1】:

    问题在于 AJAX 验证会在后台生成一个新代码(因为它是一个新请求),如果您总是针对错误的代码进行验证,就会产生这个问题。

    如果您 100% 需要使用 AJAX 验证,则必须在控制器中设置验证码操作。这样,验证码始终会在同一会话中针对相同的代码进行验证。为此,您需要:

    1. 在控制器中添加captcha 操作以创建图像:
    use yii\captcha\CaptchaAction;
    
    public function actions()
    {
        return [
            // other actions...
            'captcha' => [
                'class' => CaptchaAction::class,
            ],
        ];
    }
    
    1. 在模型规则中定义 captchaAction 指向您之前创建的控制器操作:
    function rules()
    {
        return [
            // other rules...
            ['verificationCode', 'captcha', 'captchaAction' => 'your-controller/captcha'],
        ];
    }
    
    1. 使视图中的小部件使用验证码操作而不是默认操作:
    <?php echo $form->field($model, 'verificationCode')->widget(Captcha::className(), [
        'captchaAction' => 'your-controller/captcha'
    ]) ?>
    

    更多信息:

    1. 验证码操作(控制器):https://www.yiiframework.com/doc/api/2.0/yii-captcha-captchaaction
    2. 验证码验证器(型号):https://www.yiiframework.com/doc/api/2.0/yii-captcha-captchavalidator
    3. 验证码小部件(查看):https://www.yiiframework.com/doc/api/2.0/yii-captcha-captcha

    【讨论】:

    • 我之前试过了,但是不行。表单的所有字段均已成功验证,但单击提交按钮后 - 代码不正确。
    • 您可能还需要在表单选项中禁用客户端验证
    猜你喜欢
    • 2018-07-04
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多