I need to fetch the data dynamically (as the user types) from my database. I had tried looking at the typeahead
examples, but I do not understand how could I implement the remote implementation.
<div id="remote">
<input class="typeahead" type="text" placeholder="Oscar winners for Best Picture">
</div>
$('#the-basics .typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'states',
source: substringMatcher(states)
});
This requires the array states
to be present locally. But I need to get the data from my server side script. How could I do this?
To use a remote datasource, it is recommended that you also use the bloodhound engine.
You will want to define your bloodhound instance, setting a remote option:
var taSource = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('Value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
identify: function(obj) {
return obj.Value;
},
remote: todos
});
In this instance I've created an options
hash, that holds the configuration of my remote source:
var urlRoot = '//jsonplaceholder.typicode.com';
var todos = {
url: urlRoot + '/todos',
prepare: function(query, settings) {
settings.url += '?q=' + query;
return settings;
},
filter: function(data) {
return $.map(data, function(object) {
return {
Id: object.id,
Value: object.title
};
});
}
};
In it, I define the url for my remote source, how to handle the query, and how to return the data for consumption by the typeahead.
Once I define my bloodhound instance, I then initialize it:
taSource.initialize(true);
I then define my typeahead object to use the bloodhound instance:
$('#search-input').typeahead({
hint: true,
highlight: true,
minLength: 3
}, {
name: 'myMatches',
source: taSource,
display: 'Value'
});
Here is a link to a jsFiddle demonstrating the basic use of remote sources.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.