我想在用户完成在文本框中的输入后触发ajax请求。 我不但愿它在用户每次输入字母时都运行该函数,由于这会致使不少ajax请求,可是我也不但愿他们也必须按下Enter键。 html
有没有一种方法可让我检测用户什么时候完成键入,而后再执行ajax请求? ajax
在这里使用jQuery! 戴夫 json
若是您要查找特定长度(例如邮政编码字段): 服务器
$("input").live("keyup", function( event ){ if(this.value.length == this.getAttribute('maxlength')) { //make ajax request here after. } });
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/ 函数
不知道个人需求是否有点奇怪,可是我须要与此相似的东西,这就是我最终使用的东西: post
$('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'); });
这使我能够在应用程序中包含如下元素: this
<input type="text" data-url="/controller/action/" class="update">
当用户“完成键入”(2秒钟不执行任何操做)或转到另外一个字段(元素模糊)时,哪一个更新 编码
这是一个与underscore.js防抖动功能只有一条线路 : url
$('#my-input-box').keyup(_.debounce(doSomething , 500));
这基本上是说我中止输入500毫秒后的doSomething 。 spa
有关更多信息: http : //underscorejs.org/#debounce
我正在列表中实施搜索,所以须要基于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
您会注意到,在实现此功能时无需使用任何计时器。