Javascript Jquery ajax实时验证/超时问题
我对jQuery还是有点陌生,所以可能有一个简单的解决方案,但我找不到任何东西。 我制作了这个注册表,检查用户输入用户名时是否使用了用户名或电子邮件。基本上,它只是发出一个json请求,根据用户名/电子邮件是否已被接收,返回true或false 问题是,现在如果输入文本长度超过3个字符,它基本上会在用户关注字段时对每个按键发出请求。就目前而言,这是可行的,但这需要大量的服务器请求。我希望它只在用户半秒钟没有输入时发出请求 有没有关于我如何才能做到这一点的想法Javascript Jquery ajax实时验证/超时问题,javascript,jquery,ajax,json,Javascript,Jquery,Ajax,Json,我对jQuery还是有点陌生,所以可能有一个简单的解决方案,但我找不到任何东西。 我制作了这个注册表,检查用户输入用户名时是否使用了用户名或电子邮件。基本上,它只是发出一个json请求,根据用户名/电子邮件是否已被接收,返回true或false 问题是,现在如果输入文本长度超过3个字符,它基本上会在用户关注字段时对每个按键发出请求。就目前而言,这是可行的,但这需要大量的服务器请求。我希望它只在用户半秒钟没有输入时发出请求 有没有关于我如何才能做到这一点的想法 $(document).ready(
$(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("");
}
});
}
});
})) 您可以使用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
}
您可以使用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
}
对于上次击键后等待的时间,您可以像插件那样执行操作 在这里,我向您介绍了该概念的一个简单实现: 用法:
$("#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使用我提到的插件,对edition上的代码进行语法着色。对于自上次击键以来的等待时间,您可以像插件那样执行操作 在这里,我向您介绍了该概念的一个简单实现: 用法:
$("#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使用了我提到的插件,对edition上的代码进行语法着色。谢谢,这正是我想要的。谢谢,这正是我想要的。