【问题标题】:How to cancel pending ajax request typeahead.js如何取消挂起的 ajax 请求 typeahead.js
【发布时间】:2017-05-30 08:50:34
【问题描述】:

我有一个输入字段。当此字段上有 keyup 时,我发送一个 request 。我的问题是当另一个 keyup 事件被触发时,我需要取消所有待处理的请求。我已经看到了很多答案,但我还没有找到解决方案。

var data = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.whitespace,
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        wildcard: '%QUERY',
        url: $('.typeahead').attr('data-autocomplete-url') + '?term=%QUERY',
        rateLimitBy: 'throttle',
        ajax: {
            async: true,
            dataType: 'json',
            crossDomain: true,
        }
    }

});

$('.typeahead').typeahead({
    hint: true,
    highlight: true,
    minLength: 1
},{
    name: 'company',
    displayKey: 'id',
    limit: Infinity,
    source: data,
    templates: {
        empty: [
            '<div style="margin: 4px 30px 4px 30px;" class="empty-message">',
            '  Aucun résultat trouvé   ',
            '</div>'
        ].join('\n'),
        suggestion: function(data) {
            if(data.id_db == 'more'){
                return '<p style="pointer-events:none">'+ data.text +'</p>';
            }else{
                return '<p>'+ data.text +'</p>';
            }

        }
    }
}).on('typeahead:select', function(ev, data) {
    $('#id_db').val(data.id_db);
    changeCompany($(this));
});

【问题讨论】:

标签: javascript ajax typeahead.js


【解决方案1】:

这是我使用的一个技巧。 clearTimeout 取消上一个事件。所以只有在客户端停止输入 400 毫秒后,才会进行 Ajax 调用。

(我不知道提前输入,所以使用它需要的任何事件处理......)

var timer;
$('.typeahead').on('keyup', function(e) {
  clearTimeout(timer);
  timer = setTimeout(function() {
      $.ajax({
        ...
      });
    },
    400   // Guestimate the best value you want, usually I use 300 - 400 ms
  )
});

【讨论】:

    【解决方案2】:
    var cancelprev = null;
    $("#typhead").typeahead({
        source: function(query, process) {
            var searchval = $('#searchval').val();
            
            
                if (cancelprev != null) 
               cancelprev.abort();
           
           
            var defered=$.get(requesturl,{data:searchval}).done(function(result){
                process(result.split("\n"));
            });
            
            cancelprev=defered;
        }
        
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-12
      • 1970-01-01
      • 2012-02-02
      • 1970-01-01
      相关资源
      最近更新 更多