【问题标题】:Jquery ajax live validation / timeout questionJquery ajax 实时验证/超时问题
【发布时间】:2010-11-22 02:19:13
【问题描述】:

我还是 jQuery 的新手,所以可能有一个简单的解决方案,但我找不到任何东西。 我已经制作了这个注册表单,用于检查用户输入用户名时是否使用了用户名或电子邮件。基本上它只是发出一个 json 请求,根据用户名/电子邮件是否已被占用,返回 true 或 false。

问题是,如果输入文本的长度超过 3 个字符,现在它基本上会在用户专注于该字段时所做的每一次按键都会发出请求。目前,这是可行的,但这是很多服务器请求。我希望它仅在用户没有输入(例如,半秒)时发出请求。

关于我如何能够做到这一点的任何想法?

$(document).ready(function() {
$("#user_username").keyup(function () {
    var ln = $(this).val().length;
    if (ln > 3) {
        $.getJSON("/validate/username/",
        {value:$(this).val()},
        function(data){
            if (data.reg == true) {
                $("#status-for-username").html("Username already in use");
            } else {
                $("#status-for-username").html("Username available");
            }
        });
    }
});
$("#user_email").keyup(function () {
    var ln = $(this).val().length;
    if (ln > 3) {
        $.getJSON("/validate/email/",
        {value:$(this).val()},
        function(data){
            if (data.reg == true) {
                $("#status-for-email").html("E-mail already in use");
            } else {
                $("#status-for-email").html("");
            }
        });
    }
});

});

【问题讨论】:

    标签: javascript jquery ajax json


    【解决方案1】:

    对于自上次击键后等待一段时间,您可以执行类似 jQuery.typeWatch 插件的操作。

    在这里,我向您发布了该概念的轻量级实现:

    用法:

    $("#user_username").keyup(function () {
      typewatch(function () {
        // executed only 500 ms after the last keyup event.
      }, 500);
    

    实施:

    var typewatch = function(){
        var timer = 0;  // store the timer id
        return function(callback, ms){
            clearTimeout (timer);  // if the function is called before the timeout
            timer = setTimeout(callback, ms); // clear the timer and start it over
        }  
    }();
    

    StackOverflow 使用我提到的插件,在版本中为代码着色。

    【讨论】:

    • 谢谢,这正是我想要的。
    【解决方案2】:

    您可以使用 window.setTimeout 和 window.clearTimeout。基本上触发一个函数在 x 毫秒内调用,如果事先触发另一个按键事件,则清除该处理程序并启动一个新的处理程序。

     //timeout var
     var timer;
     $('#username').keyUp( function(){
        //clear any existing timer
        window.clearTimeout( timer );
        //invoke check password function in 0.5 seconds
        timer = window.setTimeout( checkPasswordFunc, 500 );
     });
    
    function checkPasswordFunc(){
      //ajax call goes here
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-03
      • 1970-01-01
      • 2011-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多