【问题标题】:Refreshing Captcha on Ajax call在 Ajax 调用上刷新验证码
【发布时间】:2017-03-09 08:17:48
【问题描述】:

我有以下代码,用于通过 JavaScript 刷新验证码图像。无论如何我也可以使用 AJAX 请求来实现吗?

<script>
function refreshCaptcha() {
    $("#captcha_code").attr('src','captcha_code.php');
}

</script>

<button name="submit" onClick="refreshCaptcha();">Refresh Captcha</button>

【问题讨论】:

    标签: javascript jquery ajax captcha


    【解决方案1】:

    是的,这是可能的,但是您需要手动处理会话!

     <script>
     $(".RefreshCaptcha").click(function () {
         $.post('captcha_code.php', function(data, status){
             $("#captcha_code").attr('src', data);
             console.log("ajax log: " +  status);
         });         
     });
    </script>
    <button class="RefreshCaptcha">Refresh Captcha</button>
    

    w3shcools ajax.post

    【讨论】:

    • 您的脚本不工作。下面是验证码在图像标签中的输出方式。
    【解决方案2】:

    您可以使用以下代码。

    <script>
        $(document).ready(function() {
            setInterval(function() {
                $.post('captcha_code.php', function(data) {
                    $('#captcha_code').html(data);
                });
            }, 1000);
        });
    </script>
    

    【讨论】:

    • @Sachila,您的脚本不工作。下面是验证码在图像标签中的输出方式。
    【解决方案3】:

    是的,AJAX 可用于通过 Javascript 更新图像。因为代码已经使用了 jQuery,一个简单的方法是使用$.post() 发布到 PHP 脚本。假设 captach_code.php 仅返回图像源(例如 base-64 编码字符串),您可以将 src 属性设置为 response 值(例如在下面的函数 updateImage() 中)。

    function refreshCaptcha() {
        $.post('captcha_code.php', updateImage);
    }
    function updateImage(response) {
          $("#captcha_code").attr('src',response);
    }
    

    this phpfiddle 中查看它的实际应用。 注意 - 无法控制文件名,因此使用 PHP_SELF 代替 captcha_code.php

    $.post() 返回一个jqXHR object,它实现了 Promise 接口。正因为如此,可以使用.done()等类似的函数来代替指定成功回调:

    function refreshCaptcha() {
        $.post('captcha_code.php')
        .done(function(response) {
              $("#captcha_code").attr('src',response);
         })
         .fail(function() {
             //fail handler...
         })
         .always(function() {
             //handler for all cases
         });
    }
    

    this phpfiddle 中查看它的实际效果。

    【讨论】:

      猜你喜欢
      • 2011-03-30
      • 1970-01-01
      • 2012-09-15
      • 1970-01-01
      • 1970-01-01
      • 2014-09-29
      • 1970-01-01
      • 2016-01-22
      • 1970-01-01
      相关资源
      最近更新 更多