Yii2 验证码刷新或重新加载图像

Yii2 Captcha refresh or reload image

我正在使用 . I tried many time to find any api property that allows me to add Refresh image link that allows user to generate new Captcha image but I could not figure out how to do that. I tried the following 解决方案附带的高级应用程序模板的默认验证码实现,具体取决于 Jquery:

<!-- This code is placed just before the closing </body> tag at the end of
"frontend/views/layouts/main.php" -->
<script>
  $("#fox").click(function(event){
    event.preventDefault();
    $("img[id$='-verifycode-image']").click();
  })
</script>

contact.phpcontactAction 视图中,我向验证码小部件添加了一个 ID 为 fox 的 link,如下所示:

<?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [
    'template' => '<div class="row"><div class="col-lg-3">{image}<a href="#" id="fox">Refresh</a></div><div class="col-lg-6">{input}</div></div>',
]) ?>

上面描述的解决方案工作正常,但它必须为所有应用程序的视图添加不可用的代码,contactAction 视图或任何其他使用验证码的视图除外!因为我无法在包含 Jquery 库之前插入代码。即在视图中,所以我将它插入到布局的末尾。

这里的问题:yii2有没有直接的解决方案api?或者有更好的建议让这个 jquery 代码在视图中工作?即把它变成纯 JavaScript。

将其移至外部文件,应该没问题。
其他解决方案是使用验证码创建一个小部件,使用代码创建一个文件,并在调用小部件时注册 javascript 文件。
或者只是用 javascript 创建一个文件,并记得在每次显示验证码时注册它。

选择第一个解决方案,更简单,您无需构建任何东西等。在没有数千个并发用户的网站上,它会工作得很好。

下面的代码对我有用 -

视图文件上的表单代码以生成验证码图像 -

<?= $form->field($model, 'captcha')->widget(\yii\captcha\Captcha::classname(), [
    'template' => '<div class="col-lg-3">{image} <a href="javascript:;" id="fox">Refresh</a></div><div class="col-lg-3">{input}</div>',
])?> 

用于验证验证码的模型代码 -

public function rules()
{
    return [
        [['name', 'city', 'description','email'], 'required'],
        [['captcha'], 'captcha']
    ];
}

和js代码刷新layouts/main.php文件中的验证码图片-

<script>
  $("#fox").on('click',function(e){
    //#testimonials-captcha-image is my captcha image id
    $("img[id$='-captcha-image']").trigger('click');
    e.preventDefault();
  })
</script>

这样问题就解决了,我们可以创建一个中央视图作为验证码的模板,然后到处调用它。

<?php
/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model \frontend\models\ContactForm */

?>
<div class="row">
    <div class="col-lg-3">{image} <br /><a id="refresh_captcha" href="javascript:;">Refresh Captcha</a></div>
    <div class="col-lg-6">{input}</div>
</div>
<?php
$this->registerJs('
    $(document).ready(function () {
        $("#refresh_captcha").click(function (event) {
            event.preventDefault();
            $(this).parent().children(\'img\').click();
        })
    });
    ');
?>

拨打电话,您可以使用:

<?= $form->field($model, 'verificationCode')->widget(yii\captcha\Captcha::className(),[
                'template' => $this->render("/_partials/captcha_template"),
            ]); ?>

这将允许您在所有视图中 运行 它,因为每个视图的名称和 ID 可以不同。

$(this).parent().children(\'img\').click();