Yii2验证码不刷新问题

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

通过分析源码,我们只需修改\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}'
 ]);?>
复制代码

转载于:https://juejin.im/post/5aa7703df265da237f1df6d2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值