我想发送在文本字段中键入的击键,但只能以 1 秒的间隔发送。
这是为了减少在每次按键时发送 ajax 请求的负载。
所以例如。如果用户在一秒钟内键入 4 个字母,请求将发送所有这 4 个字母。假设他在 1 分钟内不停地打字,那么脚本将以 1 秒的间隔发送,直到他停止打字。
目前我的脚本是这样的:
$("#type_post").live('keyup', function() {
$.post('posts.php', {post: $("#type_post").val()});
});
但这会发送所有按键。
谁能帮帮我
更新:这是我使用的代码。
var last_post = '';
$('#type_post').focus(function() {
// check if text has been changed every second when input field is focused
setInterval(function() {
if($('#type_post').val() != last_post)
{
// if changed, post it and set the new text as last text
$.post('posts.php', {post: $("#type_post").val()});
last_post = $("#type_post").val();
}
}, 1000);
});
最佳答案
好吧,不管这个功能有多烦人,您都需要使用 setTimeout()
( info here ) 每秒运行一个函数并获取文本。如果不同,则执行 ajax 调用。
除此之外,您只希望在文本框具有焦点时启用此功能,因此您可以在“焦点”和“模糊”事件上设置一个字段和相关操作。
关于javascript - 1秒后用ajax发送击键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2069026/