我有以下Jquery代码,它监听用户在captcha中键入的内容,并在每个keyup上发送ajax请求,以查看是否键入了正确的代码:
$('#joinCaptchaTextBox').keyup(function() {
$.get('scripts/ajax/script.php', {
'join_captcha': '1',
'captcha': $('#joinCaptchaTextBox').val()},
function(data) {
var obj = JSON.parse(data);
if(obj.ajaxResponse.status) {
$('#joinCaptchaNotAcceptable').hide();
$('#joinCaptchaAcceptable').show();
}else{
$('#joinCaptchaAcceptable').hide();
$('#joinCaptchaNotAcceptable').show();
}
});
});
另一端的PHP脚本只是检查会话并回复:
if($siteCaptcha == $_SESSION['secretword']) {
$this->captchaCompare = TRUE;
}else{
$this->captchaCompare = FALSE;
}
这在95%的情况下都很好,但我发现有时它会报告键入的captcha是不正确的,尽管它是正确的。我认为这可能是因为当快速键入时,许多请求都会发送到服务器,而返回的订单或请求不是发送的订单,因此(因为只有一个是正确的)上一个是最后收到的,并且显示不正确的订单。
有更好的方法吗?有没有办法确保最后一个发送的请求是最后一个收到的?这里有我遗漏的东西吗。我可以提供更多信息。
感谢
添加一个超时,以便在用户快速键入时不会在每次按键时发送请求
$('#joinCaptchaTextBox').on('keyup', function() {
clearTimeout( $(this).data('timer') );
$(this).data('timer',
setTimeout(function() {
var data = {
join_captcha: '1',
captcha : $('#joinCaptchaTextBox').val()
};
$.ajax({
url : 'scripts/ajax/script.php',
data: data,
dataType: 'json'
}).done(function(result) {
$('#joinCaptchaNotAcceptable').toggle(!result.ajaxResponse.status);
$('#joinCaptchaAcceptable').toggle(result.ajaxResponse.status);
});
},500)
);
});