简体   繁体   English

使用jQuery的Ajax调用刷新验证码

[英]Use jQuery's ajax call to refresh a captcha

I wrote my own php captcha script, with a jpeg header, so that I can say 我用jpeg标头编写了自己的php验证码脚本,所以我可以说

<img src="captcha.php">

which works by storing the value of the captcha into the session variable. 通过将验证码的值存储到会话变量中来工作。 When the user can't read it, I want it to be refreshable. 当用户无法阅读时,我希望它是可刷新的。

I first tried 我第一次尝试

$("#refresh").click(function() {
    $("#captcha").attr("src","captcha.php");
});

but of course that doesn't make sense, and I need to make an ajax call instead. 但这当然没有意义,而我需要进行ajax调用。 How would you all recommend I do this? 你们怎么会建议我这样做?

PS I also tried PS我也试过

$.ajax({
    url: "captcha.php",
    success: function(result) {
        $("#captcha").attr("src",result);
    }
});

The first method actually makes sense to me: 第一种方法实际上对我有意义:

$("#refresh").click(function() {
    $("#captcha").attr("src","captcha.php?r=" + Math.random());
});

I assume the only thing captcha.php does is store the captcha value in session variable and outputs the captcha image, whenever its accessed. 我假设captcha.php唯一要做的就是将captcha值存储在会话变量中,并在每次访问captcha图像时将其输出。

So when you set the src of the image again and add a query string variable to it, a request is gonna be sent to the server script "captcha.php" again, which is going to then regenerate the captcha and store the new value in the session variable. 因此,当您再次设置图片的src并向其中添加查询字符串变量时,请求将再次发送到服务器脚本“ captcha.php”,该脚本将重新生成验证码并将新值存储在会话变量。

It makes sense to store the actual CAPTHCHA string in the _SESSION variable, but you should explicitly specify the state in the URL: 将实际的CAPTHCHA字符串存储在_SESSION变量中是有意义的,但是您应该在URL中明确指定状态:

$.ajax({
    url: "captcha.php?generateNew",
    success: function(result) {
        $("#captcha").attr("src","captcha.php?foo="+Math.random());
    }
});

inside your php-file: 在您的php文件中:

if(isset($_GET['generateNew']){
    $_SESSION['captchaString'] = generateCaptchaString();
}else{
    dumpCaptchaImage();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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