问题
I have twitter typeahead.js setup like this:
var filteredSource = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '@Url.Action("Get", "Search")/',
prepare: function (query, settings) {
settings.url = settings.url + $('#filter-select').val() + '?q=' + encodeURIComponent(query);
return settings;
},
rateLimitBy: 'throttle',
rateLimitWait: 800
}
});
$('#search').typeahead({
hint: false,
highlight: true,
minLength: 3
}, {
name: 'filtered-source',
display: 'value',
limit: 50,
source: filteredSource,
templates: {
empty: [
'<div>',
' Unable to find any results.',
'</div>'
].join('\n'),
suggestion: Handlebars.compile(templateData)
}
});
When user makes a search and starts typing something like "key" and makes a pause, a search request is being sent to the server by bloodhound. When user then adds letters to the input field, another search is sent to the server for example "keyword".
But the pending request "key" is first being waited to be completed by the browser and then server processes the second request and only after it has completed, results are shown.
So it can take a long time before any results are seen by the user.
Is there a way to cancel the pending request through bloodhound when the keyword is changed?
回答1:
You can use abort() function like this:
var lastSearch;
var filteredSource = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '@Url.Action("Get", "Search")/',
prepare: function (query, settings) {
settings.url = settings.url + $('#filter-select').val() + '?q=' + encodeURIComponent(query);
settings.beforeSend = function(e) {
if (lastSearch) {
lastSearch.abort();
}
lastSearch = e;
};
return settings;
},
rateLimitBy: 'throttle',
rateLimitWait: 800
}
});
This will cancel the last AJAX request done although it is important to note that the abort function will not always prevent the request from reaching the server. If the request reaches the server before abort() is called, the server may continue to process the request.
来源:https://stackoverflow.com/questions/33738325/cancel-pending-bloodhound-request-in-twitter-typeahead-js