2017-05-30 79 views
1

我有一個輸入字段。當這個字段有密碼時,我發送一個請求。我的問題是當另一個鍵盤事件觸發時,我需要取消所有未決的請求。我看到很多答案,但我還沒有找到解決方案。如何取消待處理的ajax請求typeahead.js

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)); 
}); 
+0

你可以改變你的遠程設置的一點,acchieve你想使用中止()函數是什麼。看到我的答案在這裏:https://stackoverflow.com/a/46959188/3638529 – joalcego

回答

0

這是我使用的一個技巧。 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 
) 
});