简体   繁体   中英

PHP and JavaScript: Reload captcha image

I've made my own captcha class in PHP, just to learn. It's ok, working as I want. I've tried to add a "refresh image" button but I don't know how do I do that.

form code:

<p><img src="img.php" alt="Captcha!" /></p>

img.php code:

<?php
require_once 'captcha.class.php';
$captcha = Captcha::instance(10);
echo $captcha;
?>

__toString method:

public function __toString()
{
    ob_start();
    header('Content-Type: image/jpeg');
    imagejpeg($this->drawImage(), null, 100);
    return ob_get_flush();
}

These code will output the captcha. How could I refresh this image? Something in AJAX would be great! Thank you.

您能否让重新加载对创建新验证码的页面进行AJAX调用,然后将新创建的结果返回到DIV中?

<html>
<head>
<script type="text/javascript">
    function reload()
    {
        var img = new Image();
        img.src = 'img.php';
        var x = document.getElementById('captcha');
        x.src = img.src;
    }
</script>
</head>
<body>
<a href="javascript: reload()" >Reload</a>
<img src="img.php" alt="Captcha!" id="captcha" />
</body>
</html>

Maybe a plain x.src = 'img.php' would do the trick but just to be shure it get's a new request i've made it using another image ( it allso gives you a bit more to search/learn ) .

How are you checking the captcha is correct when the form is completed? Session variable?

If it is a single session variable, you could just refresh the image using plain javascript. Adding a random query string to the end of the image url would avoid any caching issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM