是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。
@Sachila,你的脚本不工作。下面是验证码在图像标签中的输出方式。 – nackolysis