我想在用户完成在文本框中的输入后触发ajax请求。 我不希望它在用户每次输入字母时都运行该函数,因为这会导致很多ajax请求,但是我也不希望他们也必须按下Enter键。
有没有一种方法可以让我检测用户何时完成键入,然后再执行ajax请求?
在这里使用jQuery! 戴夫
#1楼
如果您要查找特定长度(例如邮政编码字段):
$("input").live("keyup", function( event ){
if(this.value.length == this.getAttribute('maxlength')) {
//make ajax request here after.
}
});
#2楼
var timer;
var timeout = 1000;
$('#in').keyup(function(){
clearTimeout(timer);
if ($('#in').val) {
timer = setTimeout(function(){
//do stuff here e.g ajax call etc....
var v = $("#in").val();
$("#out").html(v);
}, timeout);
}
});
此处的完整示例: http : //jsfiddle.net/ZYXp4/8/
#3楼
不知道我的需求是否有点奇怪,但是我需要与此类似的东西,这就是我最终使用的东西:
$('input.update').bind('sync', function() {
clearTimeout($(this).data('timer'));
$.post($(this).attr('data-url'), {value: $(this).val()}, function(x) {
if(x.success != true) {
triggerError(x.message);
}
}, 'json');
}).keyup(function() {
clearTimeout($(this).data('timer'));
var val = $.trim($(this).val());
if(val) {
var $this = $(this);
var timer = setTimeout(function() {
$this.trigger('sync');
}, 2000);
$(this).data('timer', timer);
}
}).blur(function() {
clearTimeout($(this).data('timer'));
$(this).trigger('sync');
});
这使我可以在应用程序中包含以下元素:
<input type="text" data-url="/controller/action/" class="update">
当用户“完成键入”(2秒钟不执行任何操作)或转到另一个字段(元素模糊)时,哪个更新
#4楼
这是一个与underscore.js防抖动功能只有一条线路 :
$('#my-input-box').keyup(_.debounce(doSomething , 500));
这基本上是说我停止输入500毫秒后的doSomething 。
有关更多信息: http : //underscorejs.org/#debounce
#5楼
我正在列表中实施搜索,因此需要基于Ajax的搜索。 这意味着在每次关键更改时,应更新并显示搜索结果。 这导致发送到服务器的ajax调用太多,这不是一件好事。
经过一些工作后,我采取了一种在用户停止键入时ping服务器的方法。
此解决方案为我工作:
$(document).ready(function() {
$('#yourtextfield').keyup(function() {
s = $('#yourtextfield').val();
setTimeout(function() {
if($('#yourtextfield').val() == s){ // Check the value searched is the latest one or not. This will help in making the ajax call work when client stops writing.
$.ajax({
type: "POST",
url: "yoururl",
data: 'search=' + s,
cache: false,
beforeSend: function() {
// loading image
},
success: function(data) {
// Your response will come here
}
})
}
}, 1000); // 1 sec delay to check.
}); // End of keyup function
}); // End of document.ready
您会注意到,在实现此功能时无需使用任何计时器。
来源:oschina
链接:https://my.oschina.net/u/3797416/blog/3161764