Yii2解决验证码点击、刷新页面不刷新问题

原文链接:https://www.jianshu.com/p/7455f270ebcb

首先解决刷新页面不刷新验证码问题

通过分析源码,我们只需修改\yii\captcha\CaptchaActionrun() 方法中调用为 getVerifyCode(true) 便可解决问题,但是又不能修改源码,这时可以采取继承并重载的方法来实现了。

  • 新建backend/components/CaptchaAction.php
<?php
namespace backend\components;

use yii\web\Response;

class CaptchaAction extends \yii\captcha\CaptchaAction
{

    /**
     * 默认验证码刷新页面不会自动刷新
     */
    public function run()
    {
        $this->setHttpHeaders();
        \Yii::$app->response->format = Response::FORMAT_RAW;
        return $this->renderImage($this->getVerifyCode(true));
    }

}

  • 在 SiteController 控制器中注册 CaptchaAction 方法:
public function actions()
{
    return [
        //默认验证码刷新页面不会自动刷新
        'captcha' => [
            'class' => 'backend\components\CaptchaAction',
            'testLimit' => 1,
            'maxLength' => 6,
            'minLength' => 6,
            'padding' => 1,
            'height' => 50,
            'width' => 140,
            'offset' => 1,
        ],
    ];
}

然后解决点击验证码刷问题

只需要给验证码图片标签 添加 'onclick' => 'this.src=this.src+"&c="+Math.random();'即可,其实其他框架中也一样。

<?= yii\captcha\Captcha::widget([
    'name'=>'captchaimg',
    'captchaAction'=>'site/captcha',
    'imageOptions'=>[
        'id'=>'captchaimg',
        'title'=>'换一个',
        'alt'=>'换一个',
        'style'=>'cursor:pointer;',
        // 添加点击事件
        'onclick' => 'this.src=this.src+"&c="+Math.random();'
     ],
     'template'=>'{image}'
 ]);?>

 

怎么验证提交的验证码是否正确呢?在这个例子中,登录表单提交到 'site/login',处理如下:

/*简单示例*/
public function actionLogin(){
    $post = Yii::$app->resquest->post();
    if (!$this->createAction('captcha')->validate($post['CAPTCHA'], false)) {
        //验证码错误的提示
    
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值