Yii2的Captcha使用Ajax进行验证出错 [ 2.0 版本 ]
D:\phpwork\news\controllers\SiteController.php
public function actionRegister()
{
$model = new RegisterForm();
if ($model->load(Yii::$app->request->post())) {
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$result=\yii\widgets\ActiveForm::validate($model);
return $result;
}
if($model->validate()){
$error=$model->save();
if($error) {
return $this->errorDisplay($error);
}else{
Yii::$app->session->setFlash('success');
return $this->refresh();
}
}else{
return $this->errorDisplay($model->getErrors());
}
}else{
return $this->render('register', [
'model' => $model,
]);
}
}
D:\phpwork\news\models\RegisterForm.php
['verifyCode', 'captcha', 'captchaAction'=>'site/captcha'],
报错信息:
The verification code is incorrect.
个人感觉是下面这段Ajax验证代码运行后,verifyCode就被自动刷新了:
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$result=\yii\widgets\ActiveForm::validate($model);
return $result;
}
请问大神们是怎么解决的这个问题?谢谢
阿江 补充于 2017-04-24 11:44
D:\phpwork\news\views\site\register.php
<?php $form = ActiveForm::begin([
'id' => 'contact-form',
'enableAjaxValidation'=>true,
]); ?>
<?= $form->field($model, 'member')->textInput(['autofocus' => true])->hint('Can be chinese,grapheme or number.Only use to login,not public display!') ?>
<?= $form->field($model, 'memkey')->passwordInput() ?>
<?= $form->field($model, 'memkey_repeat')->passwordInput() ?>
<?= $form->field($model, 'nickname')->textInput()->hint('Can be chinese,grapheme or number,can have blank space.For public display only!') ?>
<?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [
'captchaAction'=>'site/captcha',
'imageOptions'=>['alt'=>'点击换图','title'=>'点击换图', 'style'=>'cursor:pointer'],
'template' => '<div class="row"><div class="col-lg-3">{image}</div><div class="col-lg-6">{input}</div></div>',
]) ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'contact-button']) ?>
</div>
<?php ActiveForm::end(); ?>
阿江 补充于 2017-04-24 11:51
D:\phpwork\news\vendor\yiisoft\yii2\captcha\CaptchaAction.php
public function validate($input, $caseSensitive)
{
$code = $this->getVerifyCode();
$valid = $caseSensitive ? ($input === $code) : strcasecmp($input, $code) === 0;
$session = Yii::$app->getSession();
$session->open();
$name = $this->getSessionKey() . 'count';
$session[$name] = $session[$name] + 1;
if ($valid || $session[$name] > $this->testLimit && $this->testLimit > 0) {
$this->getVerifyCode(true);
}
return $valid;
}
看了看yii2的验证代码,验证过后session是被改变了的,有captcha的表单中怎么使用Ajax验证呢?
阿江 补充于 2017-04-24 18:21
解决掉了,解决方法参见:
Yii2验证码Captcha使用Ajax无法验证的处理方法
最佳答案
其他 2 个回答
-
johnny1991 回答于 2017-04-24 16:00 举报
['verifyCode', 'captcha','message'=>'验证码不正确'],
而不是这么写的
['verifyCode', 'captcha', 'captchaAction'=>'site/captcha'],
阿江
注册时间:2015-10-18
最后登录:2024-03-03
在线时长:186小时21分
最后登录:2024-03-03
在线时长:186小时21分
- 粉丝94
- 金钱16816
- 威望160
- 积分20276