[英]Fetching data from a remote script
我需要从数据库中动态获取数据(作为用户类型)。 我曾尝试查看typeahead
示例,但不了解如何实现远程实现。
<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)
});
这要求阵列states
在本地存在。 但是我需要从服务器端脚本中获取数据。 我该怎么办?
要使用远程数据源,建议您还使用猎犬引擎。
您将要定义您的猎犬实例,设置一个远程选项:
var taSource = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('Value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
identify: function(obj) {
return obj.Value;
},
remote: todos
});
在这种情况下,我创建了一个options
哈希,其中包含我的远程源的配置:
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
};
});
}
};
在其中,我定义了远程源的url,如何处理查询以及如何返回数据以供预输入使用。
一旦定义了猎犬实例,就将其初始化:
taSource.initialize(true);
然后,我定义我的typeahead对象以使用猎犬实例:
$('#search-input').typeahead({
hint: true,
highlight: true,
minLength: 3
}, {
name: 'myMatches',
source: taSource,
display: 'Value'
});
这是jsFiddle的链接,展示了远程源的基本用法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.