php验证码切换不刷新页面,Yii2解决验证码点击、刷新页面不刷新问题
原文鏈接:https://www.jianshu.com/p/7455f270ebcb
首先解決刷新頁面不刷新驗證碼問題
通過分析源碼,我們只需修改\yii\captcha\CaptchaAction的 run() 方法中調用為 getVerifyCode(true) 便可解決問題,但是又不能修改源碼,這時可以采取繼承并重載的方法來實現了。
新建backend/components/CaptchaAction.php
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)) {
//驗證碼錯誤的提示
}
}
總結
以上是生活随笔為你收集整理的php验证码切换不刷新页面,Yii2解决验证码点击、刷新页面不刷新问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql转化为GaussDB,Gaus
- 下一篇: php 数组到字符串的转换,php –