Yii2验证码如何脱离ActiveForm单独使用
官方提供了验证码模块(yii\captcha\CaptchaAction),但要结合ActiveForm一起用,封装得有点过度,现在有一种更加简单的用法。
1.在你的controller里引用CaptchaAction:
//WebController
class WebController extends Controller {
//引入验证码Action
public function actions() {
return [
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'maxLength' => 4,
'minLength' => 4,
],
];
}
}
这样即可使用http://www.web/captcha访问此验证码。
2.在你的html页面里,加入<img>标签
<img id="verify_image" src="/web/captcha">
使用jquery控制点击刷新:
$('#verify_image').click(function () {
$.get(
"/web/captcha?refresh=1",{},function (data) {
$('#verify_image').attr('src', data.url);
},"json"
);
});
直接刷新/web/captcha你会发现验证码是不会变新的,当加上?refresh=1参数时,会返回JSON数据:
{"hash1":466,"hash2":466,"url":"/wap/my/captcha?v=598d8247db06a"}
直接拿url这个JSON值出来赋值给img标签即可。
3.PHP端的校验:
$verifycode = \Yii::$app->request->post('verify_code');
$verifycode2 = $this->createAction("captcha")->getVerifyCode(false);
if($verifycode != $verifycode2){
//验证码错误
}