2017-02-19 57 views
0

我有以下代码,用于通过JavaScript刷新验证码图像。无论如何,我还可以通过AJAX请求来实现这一点吗?在Ajax调用上刷新验证码

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

</script> 

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

回答

0

您可以使用下面的代码。

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

@Sachila,你的脚本不工作。下面是验证码在图像标签中的输出方式。 nackolysis

0

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

<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

+0

您的脚本无法正常工作。下面是验证码在图像标签中的输出方式。 nackolysis

0

是AJAX可以用来更新的更新通过Javascript的图像。因为代码已经使用jQuery,所以使用$.post()来发布PHP脚本是一种简单的方法。假定该captach_code.php仅仅返回图像源(例如基64编码的字符串),则可以将SRC属性设置为响应值(例如,在功能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