使用AJAX的Jquery keyup事件导致不正确的结果

时间:2013-08-04 22:51:51

标签: php jquery ajax

我有以下Jquery代码,它监听用户输入验证码并在每个密钥上发送一个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%的情况下都可以正常工作,但我发现有时会报告即使正确,也会输入验证码不正确。我认为这可能是因为当快速键入时,许多请求被发送到服务器并且返回的订单或请求不是发送的订单,因此(因为只有一个是正确的)最后一个请求被接收并且显示不正确。

有更好的方法吗?有没有办法确保最后收到的最后一个请求被收到?这里有什么我想念的东西。我可以提供更多信息。

三江源

1 个答案:

答案 0 :(得分:3)

添加超时,以便在用户快速键入时不会在每个键盘上发送请求:

$('#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)
    );
});
相关问题