如何延迟发送ajax请求?


How can I make a delay for sending an ajax request?

下面是我的代码:

$("input").on('keydown', function(){
    $.ajax({
        url :  '/files/tags_autocomplete.php',
        dataType : 'JSON',
        success : function (tags) {
            $("ul").html(tags.output);
        }
    });
});

我的代码建议一些标签(那些与用户到目前为止所写的内容有匹配子字符串的标签)作为自动完成框给用户,当他输入他的标签。

我的问题是什么?我当前的代码发送一个新的ajax请求每个按键。例如,如果用户写something,我的脚本发送9个ajax请求,这看起来像一场噩梦。

不管怎样,我该如何处理呢?我的意思是,我需要实现延迟发送吗?比如"在插入最后一个字符后1秒才发送请求"?或者有更好的主意吗?

您可以创建一个简单的节流机制

$("input").on('keydown', function(){
    clearTimeout( $(this).data('timer'); )
    var timer = setTimeout(function() {
      $.ajax({
          url :  '/files/tags_autocomplete.php',
          dataType : 'JSON',
          success : function (tags) {
              $("ul").html(tags.output);
          }
      });
    }, 500);
    $(this).data('timer', timer);
});