【问题标题】:refreshing captcha code using Ajax使用 Ajax 刷新验证码
【发布时间】:2016-09-12 17:22:37
【问题描述】:

在我的页面中,我有一个 img 显示 captcha 代码和一个 img 在单击时刷新 captcha 代码,而不是整个页面。在chrome 中,它运行良好,每次单击时都会刷新代码,但在IE 中,单击img 时没有任何反应,并且要刷新captcha 代码,您必须重新加载页面。
IE这个问题怎么解决?

<img name="capImg" id="capImg" src="php/captcha.php">
<img src="images/recaptcha.png" onClick="resetCap();">

脚本:

function resetCap(){
    var ajaxRequest;
    try{
        ajaxRequest = new XMLHttpRequest();
    } catch (e){
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                return false;
            }
        }
    }
    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
            document.getElementById('capImg').src = "php/captcha.php";
        }
    }
    ajaxRequest.open("GET", "php/captcha.php", true);
    ajaxRequest.send();
}

验证码.php:

<?php
session_start();
$backImage = imagecreatefrompng('C:\xampp\htdocs\service\images\captchaBack.png');
$shadowColor = imagecolorallocate($backImage, 150, 150, 150);
$textColor = imagecolorallocate($backImage, 50, 50, 50);
$font_path = 'C:\xampp\htdocs\service\fonts\times_new_yorker.ttf';
$text = NULL;
for($i=0; $i<6; $i++) $text .= mt_rand(0,9);
$_SESSION['capCode'] = $text;
imagettftext($backImage, 28, 2, 13, 38, $shadowColor, $font_path, $text);
imagettftext($backImage, 28, 2, 15, 40, $textColor, $font_path, $text);

header('Content-type: image/png');

imagepng($backImage);
imagedestroy($backImage);
?>

【问题讨论】:

    标签: php ajax captcha


    【解决方案1】:

    使用一个唯一的参数,使浏览器再次检索图像,而不是查看缓存。这里不需要 Ajax:

    function resetCap(){
        document.getElementById('capImg').src = 
                               "php/captcha.php?" + new Date().getTime();  
    }
    

    这就是你所需要的。

    【讨论】:

    • 我测试过,每次页面重新加载后的第一次点击可以工作并更改代码,但接下来的点击在 IE 中没有任何作用
    • @Masoud 我更新了答案。你是否使用 Ctrl-F5 清理了 IE 上的缓存?
    • 非常感谢。这就是答案,在 IE 中工作得很好,但我不知道不使用 Ajax 也可以做到这一点。
    猜你喜欢
    • 1970-01-01
    • 2011-03-30
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    • 2014-09-29
    • 2016-01-22
    • 1970-01-01
    相关资源
    最近更新 更多