Use AJAX to reload captcha

2019-04-01 00:48发布

问题:

This question may have been asked already - but unfortunately, I could not find any satisfactory answers. I will just ask it for my concrete case and ask the admins not to delete the question for at least a few days so I can try it out...

I have a page. It uses a captcha. Like so:

<?php
session_start(); // the captcha saves the md5 into the session
?>
<img src="captcha.php" onclick="this.src = this.src" />

That was my first code. It did not work, because the browser condsidered it useless to reload an image if the source is the same. My current solution is to pass a get parameter:

onclick="this.src = 'captcha.php?randomNumber='+ranNum"

The JavaScript variable var ranNum is generated randomly every time the onclick event fires. It works fine, still, I don't like the possibility, if the - though improbable - case of two numbers being the same twice in a row. Although the random number varies between -50,000 and 50,000 - I still do not like it. And I don't think the method is right. I would like to know the 'righter' method, by means of AJAX. I know it's possible. I hope you know how it's possible ^^ In that case, please show me.

Thanks in advance!

By the way - if I spell cap(t)cha differently, never mind, the reference to the PHP file is right in my code: I use randomImage.php

EDIT: The random number in JavaScript is only generated so the image reloads. Captcha.php does not care for the $_GET parameter. The string really is random.

EDIT: Thus, what I would like to know is how to make the browser relaod the image without passing different get parameters every time the event fires.

回答1:

Unfortunately, AJAX doesn't provide a good way to dynamically load images. Even using the javascript "preload" trick just gets the browser to load each image once per URL. The only good way to get the browser to load another image from the same source is to use a different parameter just like you are doing now. And, like other answers have stated, timestamp should be sufficient for that.



回答2:

Have you considered using a timestamp instead?

onclick="this.src='captcha.php?ts='+Math.round(new Date().getTime()/1000)"


回答3:

Just use:

<img src="captcha.php" onclick='this.src = "captcha.php&time=" + new Date().getTime();' />

You can discard the time parameter and generate the random number in PHP. :)



回答4:

You could also get the image from an Ajax request base64 encoded and put it into the img tag too.

Of course I think it is overkill and a base64 encoded file is about 4/3 of the original's size. (A 3 kb image would be about 4kb on base64).

Edit: to have the img src attribute like

data:image/png;base64,base64encodedimage